1

I've already seen How to unregister BroadcastReceiver but it doesn't solve my problem.

On an Android Application, I register a BroadCastReceiver in the onResume() method, and I want to unregister it on the onPause() method

@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. Btw.:

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

Thanks for everything

Community
  • 1
  • 1

1 Answers1

1

Your code looks fine, but you should move super.onPause(); to top of onPause - I am not sure if this is the cause of your problems.

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?

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


[edit]

from your logcat:

java.lang.IllegalArgumentException: Receiver not registered: null

it looks like you have not initialized mRefreshReceiver and it is null, you should call:

mRefreshReceiver = new RefreshReceiver();

before calling register, or if you have such code then make sure your are not assigning null to mRefreshReceiver somewhere.

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • mRefreshReceiver is not in the manifest, because it don't inherits from BroadcastReceiver is an instance of BroadcastReceiver – Pablo Arnau González Feb 28 '14 at 11:03
  • You should move `mRefreshReceiver = new BroadcastReceiver....` outside your method (to class body), it should work fine after that. mRefreshReceiver might not get set if mIsFresh if false. Also android is recreating activity instances during config changes (like screen rotation), which I suppose might cause ensureData() to be called with mIsFresh being false. – marcinj Feb 28 '14 at 11:11
  • Solved, just changed the unregister(mRefreshReceiver); for if(registered){unregisterReceiver(mRefreshReceiver);registered = false;} – Pablo Arnau González Feb 28 '14 at 11:25