Android报错MainActivity has leaked IntentReceiver,Are you missing a call to unregisterReceiver()?

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在退出后广播接收器就会被销毁

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值