Search code examples
androidbroadcastreceiver

Does Receiver listen after app has been terminated?


I recently looked at this question and I in the code, a new receiver is registered using the registerReceiver(new BroadcastReceiver() ... method from inside the internal Activity function (called e.g. on some button click)

My question is, when app is killed, will the receiver still be active? How about if activity finishes itself and launches another activity? And what if it just undergoes the onStop() onStart() cycle or onPause() onResume()?

Should I run registerReceiver using some service? But then again, when my app is killed from some task manager, won't this kill my services as well?


Solution

  • Register the receiver in the onResume() and unregister in the onPause() in respect to the Activity lifecycle.

    private MyReceiver mReciever;
    
    ...
    ...
    
    @Override
    public void onResume(){
        super.onResume();
    
        /* Create the receiver if it doesn't exist already */
        if(mReceiver == null){
            mReceiver = new MyReceiver();
            IntentFilter filter = new IntentFilter("SOME_FILTER");
            registerReceiver(mSentReceiver, filter);
        }
    }
    
    @Override
    public void onPause(){
        super.onPause();
    
        /* Unregister the receiver if it isn't null */
        if(mReceiver != null){
            unregisterReceiver(mReceiver);
        }
    }
    

    The receiver won't be active if the app is killed (everything is lost when this happens). It is however still active if the app is in the foreground/background if the Activity/Fragment you registered it in hasn't been garbage collected yet.

    The receiver is globally active by all Activities/Fragments if it is registered via AndroidManifest too. You want to register the receiver in the Activity/Fragment when you want it only active for that particular Activity/Fragment (the two are coupled / dependent on one another). You however would use the AndroidManifest declaration if there are no dependencies on the active fragment/Activity.