onServiceConnected never called after bindService

2019-01-13 20:33发布

I have a particular situation: a service started by a broadcast receiver starts an activity. I want to make it possible for this activity to communicate back to the service. I have chosen to use AIDL to make it possible. Everything seems works good except for bindService() method called in onCreate() of the activity. bindService(), in fact, throws a null pointer exception because onServiceConnected() is never called while onBind() method of the service is. Anyway bindService() returns true. The service is obviously active because it starts the activity. I know that calling an activity from a service could sound strange, but unfortunately this is the only way to have speech recognition in a service.

Thanks in advance

8条回答
Juvenile、少年°
2楼-- · 2019-01-13 21:20

One more thing is that if you are calling bindservice method inside the oncreate method then the onserviceconnected is called after the oncreate method is finished.

So any references to the interface functions before the oncreate ends (or before onserviceconnected is called) shows null pointer exception.

查看更多
太酷不给撩
3楼-- · 2019-01-13 21:21

There can be another explanation, not a very frequent situation, but I managed to get into it and lose 2 hours to solve it.

So what I did was that I wanted to reuse the bundle from the intent received by the onBind method. But I went for the lazy version and changed the class of the intent. Apparently this causes the onServiceConnected not to get called. Probably because the system keeps a reference to the intent and uses it when calling onServiceConnected.

In conclusion don't change the intent you receive in onBind.

查看更多
登录 后发表回答