Android——Messenger

Messenger introduction

Messenger is a lightweight IPC solution. Its underlying implementation is AIDL, which can transfer data between different processes.

Server

Create a Service, process the message in the Handler, and return the Binder of the Messenger object in onBind

public class MessengerService extends Service {
    private static final String TAG = "MessengerService";

    public static final int MESSAGE_FROM_CLIENT = 20;
    @Nullable
    @Override
    //返回Binder
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
    private final Messenger messenger = new Messenger(new MessengerHandle());

    private static class MessengerHandle extends Handler{

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case MESSAGE_FROM_CLIENT:
                    //接受来自客户端的消息
                    Log.d(TAG,"" + msg.getData().getString("msg"));
                    Messenger client = msg.replyTo;
                    Message RelpyToMessage = Message.obtain(null,MainActivity.MESSAGE_FROM_SERVICE);
                    Bundle ServiceBundle = new Bundle();
                    ServiceBundle.putString("reply","Hi! Client");//返回消息至客户端
                    RelpyToMessage.setData(ServiceBundle);
                    try{
                        client.send(RelpyToMessage);
                    }catch (RemoteException e){
                        e.printStackTrace();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    }
}

Configure Service in the manifest file

<service
            android:name=".MessengerService"
            android:process=":remote"
            android:enabled="true"
            android:exported="true"/>

Client

First bind the Service of the server, then create a Messenger object based on IBinder, and then send a message to the client in the binding name, and still process the message of the server in the Handler

public class MainActivity extends AppCompatActivity{
    private static final String TAG = "MainActivity";
    public static final int MESSAGE_FROM_SERVICE = 10;//客户端发送给服务端
    private Messenger messenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(MainActivity.this,MessengerService.class);
        bindService(intent,connection,BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        unbindService(connection);
        super.onDestroy();
    }
    private  Messenger myMessenger = new Messenger(new MessengerHandle());
    //连接Service并发送消息
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messenger =new Messenger(service);
            Message message = Message.obtain(null, MessengerService.MESSAGE_FROM_CLIENT);
            Bundle bundle = new Bundle();
            //第一次向Service打招呼
            bundle.putString("msg","Hi! Service");
            message.setData(bundle);
            //接收客户端信息时,需要把服务端的Messenger通过replyTo参数传递给服务端
            message.replyTo = myMessenger;
            try{
                messenger.send(message);
            }catch (RemoteException e){
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    //接收Service的消息
    private static class MessengerHandle extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
           switch (msg.what){
                case MESSAGE_FROM_SERVICE:
                   Log.d(TAG,msg.getData().getString("reply"));
                   break;
            }
        }
    }
}

Show results

Insert picture description here

Guess you like

Origin blog.csdn.net/News53231323/article/details/114084402