问题
I am watching a behavior of Intent.FLAG_ACTIVITY_CLEAR_TOP.
For example i have three activities A,B and C Now Flow is A -> B -> C
Now when i am starting A from C with this flag with following code.
Intent intent_to_a=new Intent(C.this,A.class);
intent_to_home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent_to_a);
AFAIK, Intent.FLAG_ACTIVITY_CLEAR_TOP should remove B and should resume the A .It also does the same but in a strange way. It removes B , than removes A than creates A. Method onDestroy of A is also being called. Can anyone tell me is it proper or not? If i don't want it to get destroy what should i do?
回答1:
Use FLAG_ACTIVITY_REORDER_TO_FRONT and then use an intent to tell B to finish.
Activity B:
private BroadcastReceiver finishReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
public void onCreate() {
LocalBroadcastManager.getInstance(this)
.registerReceiver(finishReceiver ,
new IntentFilter("B-finish"));
}
public void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(
finishReceiver );
}
Activity C:
LocalBroadcastManager.getInstance(this).sendBroadcast(
new Intent("B-finish"));
Intent intent_to_a=new Intent(C.this,A.class);
intent_to_home.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent_to_a);
回答2:
Either,
1. Change the launchMode
of the Activity A to something else from standard (ie singleTask
or something). Then your flag FLAG_ACTIVITY_CLEAR_TOP
will not restart your Activity A.
or,
2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
as your flag. Then it will work the way you desire.
This question has good discussion on same topic
Android documentation says -
The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent.
If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().
来源:https://stackoverflow.com/questions/17506432/flag-activity-clear-top-destroys-target-activity-and-than-creating-it