Android IPC:onServiceConnected已调用,后跟NullPointerException
我们的应用程序通过AIDL接口连接到IPCAndroid IPC:onServiceConnected已调用,后跟NullPointerException,android,service,nullpointerexception,ipc,aidl,Android,Service,Nullpointerexception,Ipc,Aidl,我们的应用程序通过AIDL接口连接到IPC服务。到目前为止,一切都很正常,但突然我们发现在调用onServiceConnected回调后立即抛出了NullPointerException 我们通过以下方式绑定到服务: boolean isServiceBound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); 然后,我们确保服务绑定成功,后台线程等待调用onServiceConnected回
服务
。到目前为止,一切都很正常,但突然我们发现在调用onServiceConnected
回调后立即抛出了NullPointerException
我们通过以下方式绑定到服务:
boolean isServiceBound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
然后,我们确保服务绑定成功,后台线程等待调用onServiceConnected
回调:
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
Log.d(TAG, "converting Binder into IAidlService");
aidlService = IAidlService.Stub.asInterface(binder);
serviceConnected(); // this call releases background thread that waits for connection to be established
}
public void onServiceDisconnected(ComponentName className) {
Log.d(TAG, "IAidlService disconnected unexpectedly");
aidlService = null;
}
};
在调用onServiceConnected
回调期间调用serviceConnected()
后,我们假设连接已建立,并且aidlService
变量已初始化(除非onServiceDisconnected
随后被调用,但这里的情况并非如此)
正如我所说,这个方案在一段时间内运行良好,但突然我们遇到了在服务连接上的之后立即抛出的NullPointerException。Logcat输出:
01-21 14:06:32.717 22651-22651/com.xxx.xxx D/LocalService: converting Binder into IAidlService
01-21 14:06:32.721 22651-9574/com.xxx.xxx E/AndroidRuntime: FATAL EXCEPTION: IntentService[LocalService]
01-21 14:06:32.721 22651-9574/com.xxx.xxx E/AndroidRuntime: Process: com.xxx.xxx, PID: 22651
01-21 14:06:32.721 22651-9574/com.xxx.xxx E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'void com.yyy.yyy.IAidlService.someMethod(android.os.Bundle)' on a null object reference
正如您所看到的,在主线程上调用了onServiceConnected
之后,在后台线程中使用了aidlService
。我有99.9%的信心,这里没有多线程问题,并且使后台线程等待serviceConnected()
调用的逻辑工作正常(logcat中的4ms延迟支持这一说法)
我们无法复制这种行为
因此,我们知道调用了onServiceConnected
,但是没有初始化aidlService
变量。我只看到这种行为的一个潜在原因:IBinder
系统传递给onServiceConnected
的对象是null
(我100%相信IPC服务的onBind()
中返回的对象是有效的)
我在网上找不到有关此场景的任何信息,因此我的问题是:
有没有人遇到过类似的行为
是否有任何情况下,onServiceConnected
将作为第二个参数传递null
,而不是由远程服务返回的有效IBinder
多亏了@pskink的帮助,我意识到无论是使用nullIBinder调用onServiceConnected
,还是使用AIDL的存根,都不能调用onServiceConnected
一句话:不需要在onServiceConnected
回调中进行空检查。是什么阻止您使用调试器进入IAidlService.Stub.asInterface()
方法?@pskink,此代码是自动生成的,我对其进行了研究。如果bug是不可复制的,你能解释一下用调试器一步一步地检查它会得到什么吗?如果你调查了它,你可能会注意到,a接口(android.os.IBinder obj)
只能在obj
为null时返回null
,但如果你不信任AIDL
生成的代码,您根本不必使用AIDL
,并且仍然在远程对象上执行安全事务,您所需要的只是使用原始Binder
API来实现您自己的定制RPCprotocol@pskink,我明白你的意思-我被存根的代理部分搞糊涂了,但是现在我意识到,asInterface
确实只在null
参数的情况下返回null
。为了缩小范围,我将对问题进行编辑。谢谢