简体   繁体   English

无法在Android中取消注册BroadcastReceiver

[英]Can not unregister a BroadcastReceiver in Android

I've already seen How to unregister BroadcastReceiver but it doesn't solve my problem. 我已经看到了如何注销BroadcastReceiver的方法,但是它不能解决我的问题。

On an Android Application, I register a BroadCastReceiver in the onResume() method, and I want to unregister it on the onPause() method 在Android应用程序上,我在onResume()方法中注册了BroadCastReceiver,我想在onPause()方法中注销它。

@Override
protected void onResume() {
    super.onResume();

    // TODO:
    // Register the BroadcastReceiver to receive a 
    // DATA_REFRESHED_ACTION broadcast
    log("RefreshReceiver registrao");
    registerReceiver(mRefreshReceiver, new   IntentFilter(DATA_REFRESHED_ACTION));  
}

@Override
protected void onPause() {
    // TODO:
    // Unregister the BroadcastReceiver
    unregisterReceiver(mRefreshReceiver); //fails here
    Log.i("QUE PASA PEñAAA","desregitro el receptor");
    super.onPause();
}

the logcat message says it can't unregister the method. logcat消息说它无法注销该方法。 Btw.: 顺便说一句:

public static final String DATA_REFRESHED_ACTION = "course.labs.notificationslab.DATA_REFRESHED";

Thanks for everything 谢谢你所做的一切

Your code looks fine, but you should move super.onPause(); 您的代码看起来不错,但是您应该移动super.onPause(); to top of onPause - I am not sure if this is the cause of your problems. 至onPause之上-我不确定这是否是导致您出现问题的原因。

Assuming you are not unregistering receiver somewhere else, you could keep some flag whether your receiver was already registered or not, follow instructions from this SO: Correct pattern for registering a receiver? 假设您没有在其他地方注销接收器,则可以保留一些标志,以确认接收器是否已注册,请遵循此SO的指示: 注册接收器的正确模式?

Also you should swith to use LocalBroadcastManager which is better suited for local app broadcasts: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager 另外,您还应该使用LocalBroadcastManager,它更适合于本地应用程序广播: http ://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager


[edit] [编辑]

from your logcat: 从您的logcat:

java.lang.IllegalArgumentException: Receiver not registered: null java.lang.IllegalArgumentException:未注册接收者:null

it looks like you have not initialized mRefreshReceiver and it is null, you should call: 看来您尚未初始化mRefreshReceiver并且它为null,您应该调用:

mRefreshReceiver = new RefreshReceiver();

before calling register, or if you have such code then make sure your are not assigning null to mRefreshReceiver somewhere. 在调用register之前,或者如果您有这样的代码,请确保未在某处为mRefreshReceiver分配null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM