0

My app need to receiver broadcast and do something just once. The occasion might be the time my app has not started yet so I declare the receiver in the Manifest:

<receiver
    android:name=".OneShotBroadcast"
    android:permission="com.ytinrete.broadcast.accesspermisson">
    <intent-filter>
        <action android:name="com.ytinrete.broadcast.oneshot"/>
    </intent-filter>
</receiver>

And here's onReceive:

@Override
public void onReceive(Context context, Intent intent) {

    //want to doing my work here just once
    ......

}

Here comes the problem: I can't find any ways to unregister this receiver when I first get the broadcast.

I've try this:

context.unregisterReceiver(this);

But It raise the exception:

java.lang.RuntimeException: Unable to start receiver com.ytinrete.OneShotBroadcast: 
java.lang.IllegalArgumentException: Receiver not registered: com.ytinrete.OneShotBroadcast@5354a224

Currently I just set a static boolean as a flag in the receiver and it works, but I tend to find a way to unregister so that I don't need to maintain such magic variable in my project.

Is there another way to work around? Any clues will be appreciated!


Thanks to Truong Phu Quoc There's really a way to unregister: Android - how to unregister a receiver created in the manifest I've tested it and it works.

Community
  • 1
  • 1
ytinrete
  • 46
  • 6
  • 1
    Please check this link: http://stackoverflow.com/questions/6529276/android-how-to-unregister-a-receiver-created-in-the-manifest – Quoc Truong May 06 '16 at 10:01
  • @Truong Phu Quoc I've just test it and it works, how can't I find that answer for searching many times here.Thank you so much, please write an answer so I can accept it. – ytinrete May 06 '16 at 10:18

2 Answers2

0

I think you need instance of LocalBroadcastManager to unregister it

you should try to replace your

context.unregisterReceiver(this);

with

LocalBroadcastManager.getInstance(context).unregisterReceiver(this);

Hope it helps

Atiq
  • 14,435
  • 6
  • 54
  • 69
0

its not possible i think so,but if you want to receiver then registered in your activity only.and unregister in onDestroy method. if you declare it manifest file then it will be called every time when your broadcast called. you can do nothing when you dont want it.

like

if(not_required){
      return ;
} else{
\\do some with action.
}

Hope it helps.

Imtiyaz Khalani
  • 2,037
  • 18
  • 32