Skip to content Skip to sidebar Skip to footer

Using Broadcast Receiver Android To Close App

Hi am trying to use broadcast receiver to trigger some action Activity A will broadcast action 'ACTION_EXIT' and come to Main Activity. Whenever Main Activity receive the broadca

Solution 1:

Your MainActivity is paused while ActivityA is running, during which time your Receiver is unregistered, and therefore not getting the broadcast. You can accomplish what you want with result forwarding instead.

In MainActivity, start LoginActivity with the startActivityForResult() method, and override the onActivityResult() method to handle the result.

publicstaticfinalintREQUEST_CODE=0;
publicstaticfinalStringEXTRA_EXIT="exit";
...

IntentactLogin=newIntent(this, LoginActivity.class);
startActivityForResult(actLogin, REQUEST_CODE);
...

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case REQUEST_CODE:
            if(data == null) {
                return;
            }

            booleanshouldExit= data.getBooleanExtra(EXTRA_EXIT, false);

            if(shouldExit) {
                finish();
            }
            break;
        ...
    }
}

Then, in LoginActivity, add FLAG_ACTIVITY_FORWARD_RESULT to the Intent used to start ActivityA.

Intent actA = newIntent(this, ActivityA.class);
actA.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(actA);
finish();

In ActivityA, set a boolean value to indicate whether to exit, add it to a result Intent, set that as the result, and finish the Activity.

boolean shouldExit = ...            

Intent result=new Intent();
result.putExtra(MainActivity.EXTRA_EXIT, shouldExit);
setResult(Activity.RESULT_OK, result);
finish();

The result will then be delivered back to MainActivity. This can also be done with only result codes, but I prefer using Intent extras.

Post a Comment for "Using Broadcast Receiver Android To Close App"