Reputation: 406
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
Upvotes: 2
Views: 696
Reputation: 23268
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.
Upvotes: 2
Reputation: 25858
Actually you Registered the Broadcast Receiver in your main activity so its passing the context of main activity in the BroadcastReceiver so i will able to finish only that activity.
So lets screw up this what you need to do just write these lines of code in the onReceive() of Power Disconnected action receiver:
public void onReceive(Context context, Intent intent) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
}
Enjoy
Upvotes: 0