Search code examples
androidbroadcastreceiverandroid-activity

Finish two activities on receive the same broadcast


I have a BroadcastReceiver which handles System Broadcasts like AC Connected and disconnected. The BroadcastReceiver receives POWER_CONNECTED and starts an Activity "MainActivity", which unlocks KeyGuard and acquires WakeLock. In the onCreate and in onResume I register dynamically a BroadcastReceiver to listen on POWER_DISCONNECTED.

The "MainActivity" starts a second "VideoPlayer Activity", which also register a BroadcastReceiver listening on POWER_DISCONNECTED.

When I send the ACTION_POWER_DISCONNECT over adb I see through LogCat that the "MainActivity" stops first. Why?

How can I handle that the "VideoPlayerActivity" finishes first?

Thanks


Solution

  • Look here (http://developer.android.com/reference/android/content/BroadcastReceiver.html):

    Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. This is more efficient, but means that receivers cannot use the result or abort APIs included here.

    You can't guarantee that VideoPlayerActivity will receive.

    I would recommend to create a separate BroadcastReceiver (which isn't part of activities). And in this broadcast receiver do something like this:

    videoPlayerActivity.finish();
    mainActivity.finish();
    

    Sure, you need to initialize both of these variables in onCreate or onResume of your activities.