Android在MainActivity中动态注册广播接收器时,报了MainActivity has leaked IntentReceiver的错,具体的错误信息栈如下(部分涉及到公司的信息的包名被我用*代替,但是并不影响阅读)
04-29 00:23:35.424 3586-3586 E/ActivityThread: Activity **.**.serviceexplore.MainActivity has leaked IntentReceiver **.**.receiver.ScreenStatusReceiver@2b5348de that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity **.**.serviceexplore.MainActivity has leaked IntentReceiver **.**.receiver.ScreenStatusReceiver@2b5348de that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:903)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:704)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1651)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1631)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1625)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:489)
at **.**.serviceexplore.MainActivity.onCreate(MainActivity.java:66)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
出现这个错误的原因是在Activity中注册广播时,没有在onDestory回调中清除广播注册,所以在任务栈销毁时会报错。
解决方法:在onDestory回调中清除了就好
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
相关建议:使用service动态注册相关广播,因为service即使退出应用后依然可以在后台运行,activity在退出后广播接收器就会被销毁