我在 Android 中创建了以下实体:-
- Android MyService (APK)
- MyServiceClient (jar)
- MyApplication(通过 MyServiceClient 使用 MyService)
对于 IPC,我使用了 AIDL。下面给出了一个示例实现(服务客户端)。
AIDL 接口 - ICLAZZ.aidl(在服务端实现,内部用于带服务的 IPC) 服务客户端 - CLAZZ.java(向开发人员公开的 API)
ICLAZZ.aidl
interface ICLAZZ {
void doSomething();
}
CLAZZ.java
public class CLAZZ
{
private ICLAZZ mSvcInstance; //remote object
// static method, instead of constructor for object creation due to some reason
public static synchronized CLAZZ getInstance(inputParam)
{
// ICLAZZ remoteObject = get the remote object from service
if(remoteObject!=null) {
INSTANCE = new INSTANCE(inputParam);
INSTANCE.mSvcInstance = remoteObject;
}
return INSTANCE;
}
private CLAZZ() {
}
private CLAZZ(inputParam) {
// initialize based on inputParam
}
public void doSomething() {
if(mSvcInstance!=null)
mSvcInstance.doSomething();
}
};
当 API 用户调用 CLAZZ.getInstance() 时,我创建了一个远程对象实例并将其保存在 CLAZZ 的本地对象中,并将 CLAZZ 对象返回给用户。
我面临的问题是,如果服务重新启动,所有以前的远程对象都会失效。但是,API 用户可能已经保存了之前创建的 CLAZZ 对象,并且可能希望在其上调用一些功能。这将导致应用程序失败。此外,我不想保留应用程序创建的 API 对象的任何全局列表。在给定的场景中,是否有某种机制可以让我优雅地处理这种情况并为现有对象提供恢复。