BroadcastReceiver多次unregisterReceiver 导致 Receiver not registered问题

转载请注明出处:http://blog.csdn.net/guiping_ding/article/details/50997230

注销广播接受器的时候出现该错误:

java.lang.IllegalArgumentException: Receiver not registered: com.xxx.popuwindow.member.MemberBaseCard$1@41624e70
    at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:657)
    at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1362)
    at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:445)
    at com.xxx.popuwindow.member.MemberBaseCard.stopSendCommand(MemberBaseCard.java:88)
    at com.xxx.popuwindow.member.MemberBaseCard.dismiss(MemberBaseCard.java:95)
    at com.xxx.popuwindow.RightPopWindowDialog$1.onDismiss(RightPopWindowDialog.java:52)
    at android.widget.PopupWindow.dismiss(PopupWindow.java:1278)
    at com.xxx.popuwindow.RightPopWindowDialog.dismiss(RightPopWindowDialog.java:126)
    at com.xxx.popuwindow.member.MemberBaseCard.dismiss(MemberBaseCard.java:96)
    at com.xxx.popuwindow.member.MemberPayPop.onClick(MemberPayPop.java:245)
    at android.view.View.performClick(View.java:4204)
    at android.view.View$PerformClick.run(View.java:17355)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    at dalvik.system.NativeStart.main(Native Method)

出现这个错误的原因就是 该广播接受器已被注销,导致找不到该广播接收器.解决办法就是加一个Tag标识.详细见代码:

private boolean mReceiverTag = false;   //广播接受者标识
//代码中动态注册广播
private void registerReceiver() {
        if (!mReceiverTag){     //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
            IntentFilter mFileter = new IntentFilter();
            mReceiverTag = true;    //标识值 赋值为 true 表示广播已被注册
            mFileter.addAction("com.android.scan.RECEIVED_CODE_FROM_NFC");
            this.registerReceiver(mReceiver, mFileter);
        }
}
//注销广播
private void unregisterReceiver() {
        if (mReceiverTag) {   //判断广播是否注册
                mReceiverTag = false;   //Tag值 赋值为false 表示该广播已被注销
                this.unregisterReceiver(mReceiver);   //注销广播
        }

}

代码中动态注册广播,记得在界面关闭的时候注销广播.不然会有多个广播接受者存在.记得代码中
registerReceiverunregisterReceiver 成对存在.

你可能感兴趣的:(Android点滴)