10

I am wondering if I could share a singleton on the application context across multiple applications? Each application would be in its own APK but This might sound like bad architecture but hear me out first.

The reason I would like to do this is because I have an existing library which controls an external device over bluetooth. The library is java but under the covers there is allot of native (c/c++) all wrapped by java. I have looked at putting this all in a service but the IPC (I was using aidl) becomes very cumbersome fast. Trying to reduce object to primitives is next to impossible (private fields, jni pointers etc) and trying to wrap everything with AIDL is very messy.

If each app could run in the same process and also have the same application context hence allowing me to keep a singleton object on there that would make things much easier. My googl-fu is failing me on this one. Maybe its not possible?

4

2 回答 2

11

这应该是可能的,但是您会遇到问题,因为您仍在运行两个不同的 APK,每个 APK 都有自己的 ClassLoader。由于不同 ClassLoader 加载的同一个 Class 被认为是完全不同的,所以你不能从 APK A 创建一个 Class 并期望 APK B 能够访问同一个 Class。但是,一个漏洞是同一进程中的Android系统类总是由同一个ClassLoader加载,因此解决方案是通过Android系统类(例如System.set/getProperty)来存储您的数据。您可以在此处阅读有关此技术的优秀文章。

由于您希望存储比 Java 原语更复杂的数据,并且考虑到上述方法会严重限制您可以存储的数据结构,因此最终可能仍然认为 AIDL 是您的最佳选择。但是,如果您将两个 APK 放在同一个进程中,至少您的数据不需要跨越进程边界,因此它应该是相当有效的。

于 2013-07-16T03:31:56.487 回答
9

是的他们可以。您只需要在两个应用程序中分配相同的值android:sharedUserIdandroid:process使用相同的证书对其进行签名。

相关链接:

于 2013-07-15T21:32:52.700 回答