About the flag and Startup Mode of Android Activity, androidactivity
Recently, due to project requirements, You need to press a button to return to the specified Activity. It may be that several activities are returned consecutively. The first thought is to write a few more finish ()...... if you want to roll back to Activity A, you can set the Startup Mode of Activity A to singleTask in Manifest. add A sentence in the declaration of A in xml: Android: launchmode = "singleTask". Of course, this will cause all the activities above A in the Activity stack to be cleared every time A is started.
There is no problem in writing this way. When the program returns, it will call the finish () method of all the activities above A in the Activity stack, and then reuse. Because I saw some Activity flags by the way, I thought that FLAG_ACTIVITY_CLEAR_TOP can also achieve this effect. Considering that everyone seems to be using FLAG_ACTIVITY_NEW_TASK together, although I see the document that FLAG_ACTIVITY_NEW_TASK is redundant, it also takes into account that if the returned Activity does not exist ..... let's take a look, so we have:
Intent intent = new Intent (this, A. class );
Intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_NEW_TASK );
StartActivity (intent );
Then the crash started .. After checking for a long time, we found that:
FLAG_ACTIVITY_CLEAR_TOP: if an instance of the activity type that can respond to this intent already exists, all activities on this instance will be cleared so that they are located at the top of the stack to respond to intent. If the loading mode of the specified activity is"standard"(By default), it will also be removed from the stack, and a new instance will be loaded to process the arrival intent. This is because the loading mode is"standard"Activity will always create a new instance to handle the new intent.
That is, in this case, A will first destroy and then create. Therefore, if the onDestroy method of a is rewritten to release the resource, the resource will be released twice, if we set the loading mode to singleTask, we don't need addFlags anymore. Just start it directly... By the way:
FLAG_ACTIVITY_NEW_TASK: If a task with the same affinity as the new activity already exists, the activity will be loaded into that task. If no, the new task is enabled.
We can also create a list in the Application subclass to manage the Activity. The main method is to inherit the interface, override OnActivityCreated, and OnActivityDestroy, corresponding to list. add, list. the remove Method. When we need to return to a specific Activity, we can perform finish () on the Activity above it in the list, because the Android :: launchmode = "singleTask" is relatively simple ~