Messenger interprocess communication (IPC)

Internal messenger is achieved aidl communication, it can be seen as a lightweight aidl, but relatively simple. A service first turns on and realized a Handler for handling messages, the method returns IBinder object onbind by Serviceconnect binding service, and IBinder objects to pass parameters Serviceconnect in IBinder IBinder create objects in the message and sends a bundle onServiceConnected the message

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        Intent intent = new Intent(MainActivity.this, MyService.class);
        bindService(intent,mConnection,BIND_AUTO_CREATE);

    }
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            Messenger messenger = new Messenger(iBinder);
            Message message = Message.obtain(null, 1);//获得一个message对象,并设置what标记为1
            Bundle bundle = new Bundle();
            bundle.putString("msg","msgisme");
            message.setData(bundle);
            try {
                messenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };





    @Override
    protected void onDestroy() {
        unbindService(mConnection);
        super.onDestroy();
    }
}

The above is the main activity Code

public class MyService extends Service {
    public MyService() {
    }

    private static final String TAG = "yjm";

    private static class abchandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
//                Log.e(TAG,msg.getData().getString("msg"));
                System.out.println(msg.getData().getString("msg"));
            }
            super.handleMessage(msg);
        }
    }


    private Messenger messenger=new Messenger(new abchandle());
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}

The above is to create a service code

Guess you like

Origin www.cnblogs.com/Ocean123123/p/10956661.html