Where to sign up for BroadcastReceiver (activity activity fun)

In what place should the registrant of intent be registered / deregistered with the Office? I would usually add the following here:

class MyActivity 
{
    private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v(TAG, "Do something.");
        }
    };

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

        registerReceiver(mMyReceiver, new IntentFilter(...));
    }

    @Override
    public void onPause() {
        super.onPause();

        unregisterReceiver(mMyReceiver);
    }
}

The problem is that my activity may stop responding to the broadcast if this happens when it is in a pause state. Where is the right place for something like this?

thank

+3
source share
3 answers
+2
source

This should work in your case:

Unregister in onDestroy(). 
+2
source

, onCreate() onDestroy(). , , , .

I had the opposite problem. I initially registered my receivers in onCreate (), and when my activity was paused, I still have logs that they receive broadcasts. I moved it to onResume, just like yours, and this problem disappeared.

+1
source

Source: https://habr.com/ru/post/1791722/


All Articles