Messenger实现进程间通信(IPC)
阅读原文时间:2023年07月08日阅读:3

messenger内部也是实现aidl通信,所以可以看做一个轻量级aidl,但相对比较简单.首先开启一个服务并实现一个Handler用来处理消息,在onbind方法中返回IBinder对象,通过Serviceconnect绑定服务,并把IBinder对象传递到Serviceconnect的IBinder iBinder 参数中.在onServiceConnected中创建message对象并发送带bundle的消息

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();  
}  

}

上面是主activity代码

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();  
}  

}

上面是创建服务代码