3

I have a BroadcastReceiver in my app, and it was defined in AndroidManifest.xml as below:

<receiver android:name=".receiver.MyTaskReceiver">
    <intent-filter>
        <action android:name="xxx.xxx.xxx" />
    </intent-filter>
</receiver>

This is the MyTaskReceiver code :

public class MyTaskReceiver extends BroadcastReceiver {

    private ReceiverListener listener ;

    @Override
    public void onReceive(Context context, Intent intent) {
        //do general things

        if(listener != null) {
            listener.received();    //do special things if the listener is setted up.
        }
    }

    public void setListener(ReceiverListener listener) {
        this.listener = listener;
    }

    public interface ReceiverListener {
        void received();
    }

} 

When the receiver got a intent, I will do some general things first, like save data...

But if the specified activity is displayed to the user, I need to do change the activity's views, so I use the ReceiverListener to do this. Set a listener to the MyTaskReceiver in onCreate and set null in onDestroy.

Then here comes an issue, how can to get the instance of the MyTaskReceiver so that I can set a listener to it?

Or is there any other ways to achieve what I want ?

Thanks.

L. Swifter
  • 3,179
  • 28
  • 52
  • You do not need the reference to a receiver when it is defined in Manifest file. Just handle the intent in your BroadcastReceiver class. – Talha Jul 26 '16 at 07:21
  • 2
    Unfortunately that's not how receivers works. The instance will be created, the `intent` delivered to `onReceived` and then destroyed. You can't register listener to it. Take a look on @Natalia answer. That seems to be what you're looking for. – Budius Jul 26 '16 at 07:27
  • @Budius your comment is the answer I want, thank you. – L. Swifter Jul 26 '16 at 08:09

1 Answers1

5

You can register receiver in your activity like this:

private void registerBroadcastReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(xxx.xxx.xxx);
    registerReceiver(this.broadcastReceiver, intentFilter);
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        //do whatever need to be done
    }
};

Hope it helps! :)

And remember to unregister your receiver (for example in onDestroy())

unregisterReceiver(this.broadcastReceiver);
Natalia
  • 681
  • 5
  • 12
  • 1
    I know I can register BroadcastReceiver in an activity, but my receiver doesn't depend on a special activity, I need it works when the app is running not an activity is running. And thanks anyway :) – L. Swifter Jul 26 '16 at 07:33