Service not registered解决方案

我的问题如下,读者看一下是不是和我的一样。
问题描述:
在创建 前台服务时, 建立了一个通知Notification, 当在活动中使用
bindService(intent, connection, BIND_AUTO_CREATE);后,我们启动了前台服务,模拟器也能看到通知的创建,然后我点击了通知。
因为通知设置了setContentIntent(Pi),
Intent intent = new Intent(this, Activity.class);
PendIntent pi = PendIntent.getActivity(this,0,intent,0);
所以点击通知后会跳转到活动Activty中,
然后,你再 unbindService(connection)时,系统崩溃了,LogCat日志中显示Service not registered

原因分析:

Service not registered是因为没有调用bindService(), 却调用了
unbindService(), unbindService并没有找到connection对象,找不到启动的服务,所以报错了。

疑问:

我明明点击了bindService()怎么会找不到Service呢?

结论:
问题出在了
因为通知设置了setContentIntent(Pi),
Intent intent = new Intent(this, Activity.class);
PendIntent pi = PendIntent.getActivity(this,0,intent,0);
所以点击通知后会跳转到活动Activty中,而活动的LauchMode默认是Standard, 所以会重新创建一个新的活动,之前活动里的connection对象自然也就获取不到了。
解决方案

  1. 要找回connection对象还不简单吗, 按一下返回键不就回到了上一个活动,此时再调用unbindService()就能关闭服务了,也不会报错。
  2. 或者 将 这个活动的启动模式LauchMode设置为 栈顶复用模式
    SingleTop;那样点击通知就不会启动新的活动了

废话在后
作者怎么说了那么多没用的废话呢?废话?这不是给您讲清楚这个问题出现条件,出现原因,以及解决方案嘛

猜你喜欢

转载自blog.csdn.net/qq_41904106/article/details/115105671