8) 10 minutes to learn the android--activity life cycle stop and restart

Source: Internet
Author: User

It is important to properly stop and restart our activity, and in the activity lifecycle, they can ensure that the user perceives that the program exists without losing their progress. In the following key scenarios, stop and restart are involved:

    • Our app is stopped when the user opens the most recently used app menu and switches from our app to another app. If the user returns to our app via the launcher icon on the main screen of the phone or the Recently Used program window, our activity will restart.
    • The user initiates a new activity in our app, and the current activity will stop after the second activity is created. If a user clicks the Back button, the first activtiy will be restarted.
    • Users receive a call call when they use our app.

The activity class provides the OnStop () and Onrestart () methods to allow calls to be made when activity stops and restarts. Unlike a partially blocked UI in a paused state, the stop State is that the UI is no longer visible and the user's focus shifts to another activity.

Note: because the system saves instances of activity in memory when the activity is stopped, it is sometimes not necessary to implement OnStop (), Onrestart () or even the OnStart () method. Because most of the activity is relatively simple, the activity stops and restarts itself, we only need to use OnPause () to stop the running action and disconnect the system resource link.

Figure 1. Display: When the user leaves our activity, the system calls OnStop () to stop the activity (1). At this point, if the user returns, the system calls Onrestart () (2) and then quickly calls OnStart () (3) with Onresume () (4). Note: The system will always call the OnPause () method before OnStop (), regardless of the cause of activity stopping.

Stop activity

When activity calls the OnStop () method, activity is no longer visible, and all resources that are no longer needed should be freed. Once the activity is stopped, the system destroys its instance ( associated with the stack structure, which usually causes the previous activity to be destroyed ) when the memory space is needed. In extreme cases, the system directly kills our app process and does not execute the activity's OnDestroy () callback method, so we need to use OnStop () to free up resources, thus avoiding memory leaks. (this requires attention)

Although the OnPause () method is called before OnStop (), we should use OnStop () to perform shut-down operations on those CPU intensive, such as writing information to the database.

For example, here is an example of saving a draft of a note to persistent storage in the OnStop () method:

@Overrideprotected voidOnStop () {Super. OnStop ();//Always call the superclass method First//Save The note ' s draft, because the activity is stopping//And we want to being sure the current note progress isn ' t lost.Contentvalues values =Newcontentvalues ();    Values.put (NotePad.Notes.COLUMN_NAME_NOTE, Getcurrentnotetext ());    Values.put (NotePad.Notes.COLUMN_NAME_TITLE, Getcurrentnotetitle ()); Getcontentresolver (). Update (MUri,//The URI for the note to update.Values//The map of column names and new values to apply to them.            NULL,//No SELECT criteria is used.            NULL     //No WHERE columns is used.            );}

After the activity has stopped, the activity object is saved in memory and recalled during activity resume. We do not need to reinitialize those components that are stored in memory before reverting to the resumed state. The system also saves the current state of each view in the layout, and if the user enters text in the EditText component, it is saved and therefore does not need to be saved and restored.

Note: Even if the activity is stopped at activity stop, it will still save the state of the View object (such as the text in EditText) into a bundle and restore them when the user returns to the activity (The next section describes how to use bundles to hold other data when the activity is destroyed and re-established.)

Start and restart activity

When activity returns to the foreground from the stopped state, it calls Onrestart (). The system calls the OnStart () method again, and the OnStart () method is called each time the activity is visible. The Onrestart () method is called only when the activity is resumed from the stopped state, so we can use it to perform some special recovery (restoration) work, and notice that it was previously stopped rather than destrory.

It is less common to use Onrestart () to restore activity state, so there is no guidelines for how this method is used. However, since the OnStop () method should do the cleanup of all activity resources, we need to re-instantiate those resources when we restart activtiy, and we also need to instantiate those resources when the activity is first created. In the above reason, you should use OnStart () as the corresponding method for OnStop (). OnStart () is called when the activity is created and the activity is restarted from the stop state. That is, what we do in the onstop, it should be in the onstart to re-create the deleted resources.

For example, because the user is likely to have a long time before returning to the activity, the OnStart () method is a good place to verify that some of the necessary system features are available.

@Overrideprotected voidOnStart () {Super. OnStart ();//Always call the superclass method First//The activity is either being restarted or started for the first time//So the is where we should make sure the GPS is enabledLocationmanager Locationmanager =(Locationmanager) Getsystemservice (Context.location_service); Booleangpsenabled =locationmanager.isproviderenabled (Locationmanager.gps_provider); if(!gpsenabled) {        //Create A dialog here this requests the user to enable GPS, and use an intent//With the Android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS ACTION//the user to the Settings screens to enable GPS when they click "OK"}} @Overrideprotected voidOnrestart () {Super. Onrestart ();//Always call the superclass method First//Activity being restarted from stopped state}

When the system destory our activity, it calls the OnDestroy () method for the activity. Because we are doing the freeing of resources in the OnStop method, the Ondestory method is the last thing we want to do is to clear the areas that could lead to a memory leak. It is therefore necessary to ensure that those threads are destroyed and all operations are stopped.

8) 10 minutes to learn the android--activity life cycle stop and restart

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.