Search code examples
androidbroadcastreceiverandroid-lifecycle

I can't stop receiving broadcasts


I can't stop receiving broadcasts. Why?

This is the code I have:

public class MainActivity extends AppCompatActivity {

    BroadcastReceiver br = new CustomReceiver();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BroadcastReceiver br = new CustomReceiver();
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        this.registerReceiver(br, filter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(!br.isOrderedBroadcast())
            this.registerReceiver(br, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(br.isOrderedBroadcast())
            this.unregisterReceiver(br);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(br.isOrderedBroadcast())
            this.unregisterReceiver(br);
    }

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

        if(!br.isOrderedBroadcast())
            this.registerReceiver(br, filter);
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if(br.isOrderedBroadcast())
            this.unregisterReceiver(br);
    }
}

public class CustomReceiver extends BroadcastReceiver {

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

        String intentAction = intent.getAction();
        String toastMessage = "TOAST";

        switch (intentAction){
            case Intent.ACTION_POWER_CONNECTED:
                toastMessage="Power Connected!";
                break;
            case Intent.ACTION_POWER_DISCONNECTED:
                toastMessage="Power Disconnected!";
                break;
        }
        Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
    }
}

When I go to onPause() and onStop() the app continues to show toast message of connect and disconnect charge. I don't know why.


Solution

  • My guess is that condition (which you're using in onPause() and onStop()) br.isOrderedBroadcast() is false so CustomReceiver won't get unregistered.

    Also, according to the documentation, you should register/unregister CustomReceiver either in onCreate()/onDestroy() or in onResume()/onPause().