Android 进程间通讯之通过Intent+bundle实现跨进程通讯

跨进程通讯可以通过Intent中附加extras的方式、通过共享文件的方式、通过messenger的方式、通过aidl的方式、通过ContentProvider的方式、通过网络的方式(Socket)。

这里记录通过使用Bundle实现IPC,由于Bundle实现了Parcelable所以它可以方便的在不同进程间传输,Intent可以在Activity、Service和BroadcastReceiver中传递Bundle数据,因此可以通过bundle附件需要传输的信息借助Intent发出去。Bundle支持传输的类型有很多具体可以看其支持的类型,如基本类型、实现了Parcelable或Serializable接口的对象。实例代码如下:

  Bundle bundle = new Bundle();
    bundle.putString("test", "来自A");
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    ComponentName cn = new ComponentName("com.test",
            "com.test.MainActivity");//要启动的目标包名和包名+类名
    intent.setComponent(cn);
    intent.putExtras(bundle);
    startActivity(intent);

参考资料:任玉刚《Android开发艺术探索》 刚神csdn地址:https://me.csdn.net/singwhatiwanna

你可能感兴趣的:(Android)