我使用的是前台Android Service
,每60秒通过REST API通过Retrofit请求资源。此类服务的运行过程与应用程序不同,这是必需的,因此,当进入休眠模式时,Android不会杀死它。
public class ResourceService extends Service {
...
private BroadcastReceiver mReceiver;
@Override
public void onCreate() {
super.onCreate();
// create mReceiver (BroadcastReceiver)
// create intentFilter (IntentFilter)
registerReceiver(mReceiver, intentFilter);
}
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// main logic
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
注销应用程序时,将调用onDestroy()
方法,因此也会调用unregisterReceiver()
。该应用程序将按预期进行登录活动,该服务成功停止。但是,logcat会出现以下异常:
09-18 09:30:06.627 849-849/foo.mycompany.es.myapp:externalProcess E/ActivityThread: Service foo.mycompany.es.myapp.resources.ResourcesService has leaked IntentReceiver foo.mycompany.es.myapp.resources.ResourcesService$2@7c90278 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service foo.mycompany.es.myapp.resources.ResourcesService has leaked IntentReceiver foo.mycompany.es.myapp.resources.ResourcesService$2@7c90278 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1222)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:993)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1348)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1328)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1322)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:630)
at foo.mycompany.es.myapp.resources.ResourcesService.registrarReceptor(ResourcesService.java:104)
at foo.mycompany.es.myapp.resources.ResourcesService.onCreate(ResourcesService.java:74)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3534)
at android.app.ActivityThread.-wrap6(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1732)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
我已经看到有关该主题的similar answer,但它指的是活动。这样的答案状态unregisterReceiver()
应该放在onPause()
方法中,但是在Service
超类中没有这样的方法可以覆盖。
有人知道上述错误的原因是什么吗?
谢谢。
答案 0 :(得分:1)
在onstart命令中调用unregisterReceiver(locationReceiver)
答案 1 :(得分:0)
在调用super.onDestroy()之前尝试注销接收器
@Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}