android - 在进程之间共享 Activity 对象的正确方法是什么?

标签 android ipc aidl android-binder

我正在研究在两个进程之间共享 Activity 对象,但是有关它的文档通常乏善可陈,有时 even incorrect.

具体来说,我正在研究通过包裹共享 Binder 对象。文档说明。

Active Objects

An unusual feature of Parcel is the ability to read and write active objects. For these objects the actual contents of the object is not written, rather a special token referencing the object is written. When reading the object back from the Parcel, you do not get a new instance of the object, but rather a handle that operates on the exact same object that was originally written. There are two forms of active objects available.

Binder objects are a core facility of Android's general cross-process communication system. The IBinder interface describes an abstract protocol with a Binder object. Any such interface can be written in to a Parcel, and upon reading you will receive either the original object implementing that interface or a special proxy implementation that communicates calls back to the original object. The methods to use are writeStrongBinder(IBinder), writeStrongInterface(IInterface), readStrongBinder(), writeBinderArray(IBinder[]), readBinderArray(IBinder[]), createBinderArray(), writeBinderList(List), readBinderList(List), createBinderArrayList().

但是当收到包裹时,返回的对象只是一个BinderProxy,不能转换为原始类,也不能实现除基本IBinder调用之外的任何调用。虽然这显然是文档中引用的代理对象,但我想知道引用同一语句中提到的原始对象的方法是什么。

我还想知道是否有资源可以更彻底地解释或记录这个主题。

最佳答案

假设它正确实现了 Parcelable 接口(interface),您应该能够将对象转换为其原始类。类型转换它就像这样:

// in ProcessDataActivity retrieve User 
Intent intent = getIntent();
ParcelableObjectExample usr = (ParcelableObjectExample)
     intent.getParcelableExtra("parcelableExample");

要成功,您需要在 ParcelableObjectExample 上正确实现 Parcelable 接口(interface),为此您必须:

  1. 实现它的 describeContents 方法
  2. 实现其抽象方法 writeToParcel,获取对象的当前状态并将其写入 Parcel
  3. 在我们的类中添加一个名为 CREATOR 的静态字段,它是一个实现了 Parcelable.Creator 接口(interface)的对象
  4. 添加一个以 Parcel 作为参数的构造函数。 CREATOR 调用该构造函数来重建我们的对象。

关于android - 在进程之间共享 Activity 对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544594/

相关文章:

未找到 Android native 库

java - 如何将Android图片下载器修改为AsyncTask

android - react native :how to understand device is rooted?

linux - IPC 使用 msgsnd 和 msgrcv

java - 由于 java 文件中的 "missing"Parcelable 类,Android Studio/Gradle 无法构建

Android:AIDL 拒绝从定义 parcelable 的 aidl 文件生成代码

methods - .aidl 文件中的方法是否有 "@Deprecated"注释?

java - 为什么我的 RecyclerView 更新了而我没有通知适配器?

winapi - Win32 PulseEvent() 函数的替代方法是什么?

electron - electronic-quick-start,ipcMain,CSP在Javascript中阻止 'eval'