Android. App. Activity

Source: Internet
Author: User
Basic class, must be familiar. To use it, you must derive your own activity subclass from activity.
It can be considered as the smallest independent task unit for interaction with users, so it is called "activity ". When an activity interacts with a user and completes the work, multiple Java threads can assist the activity.
Almost all activities need to interact with users. Therefore, they need to create their own UI, which is often full screen. Of course, it can also be made into a floating window, or embedded into other activities to form a combination.

Two methods must be implemented:
-Oncreate (bundle)
Put the activity initialization code here. Setcontentview (INT) and findviewbyid (INT) are often used to set the UI element.
-Onpause ()
When a user does not need to interact with the activity and leaves, the system calls back this method. Save User Data here! (Contentprovider is often used)

To start an activity using context. startactivity (), you must configure the <activity> attribute in the androidmanifest. xml file.

Activity is the most important component of an android application. It affects the life cycle, composition, and Startup Mode of the application. For more information, see application basics and task and activity stacks.

All "activities" in the Android system are organized and managed in the form of "activity stacks. When an activity is created, it is placed on the top of the stack and becomes "active. Other activities are under it. When will the activity exit, the following activity will be on top again.

Activity has four states:
1> if it is displayed on the screen and receives user input, it is on the top of the stack and is "active" (running.
2> if it is displayed on the screen but cannot receive user input and loses focus, other transparent or non-full-screen activity exists on it. This is a paused state ). For a paused activity, all its internal information still exists and is still connected to the "Window Manager. However, it is possible that the system will forcibly kill the system when the memory is very short.
3> If an activity is completely blocked by other activities and is invisible, it is in the stopped state ). It is still in the internal state, but its window is hidden and is often forcibly killed by the system when the memory is tight.
4> when an activity is paused or stopped, it will be terminated by the System Command (finish) or forcibly killed. When the user restarts it and obtains the focus again, it is equivalent to restarting and needs to be restored.

This involves seven callback functions:
1> oncreate () starts from scratch
2> oncreate ()-> onstart ()-> onresume () is visible and can interact with users.
3> run other applications and overwrite them.-> onpause ()
4> it is completely invisible.-> onstop ()
5> when it is in the "paused" status, the user reselect it and-> onresume () re-obtains the focus
6> when the instance is in the "STOPPED" status, the user selects it again.-> onrestart ()-> onstart ()-> onresume ()...
7> when it is in the "STOPPED" status, ignore it for a long time, with less memory.-> ondestroy ()
8> when the system is in the "paused" or "STOPPED" status, the memory is tight and killed by the system. No callback at this time!

There are three more key points:
1> complete lifecycle
Start with oncreate () and end with ondestroy. Therefore, an activity needs to initialize in oncreate () and release resources in ondestroy.
2> visible Lifecycle
Start with onstart () and end with onstop. During this period, the user can see the activity on the screen (it may be blocked in the background and does not interact with the user ). Maintain the resources to be displayed on the UI in these two methods.
For example, register (Register) A broadcastreceiver in onstart () to monitor the events that affect the UI; sell Registration (unregister) in onstop () because the user can no longer see the UI.
Onstart () and onstop () can be called back multiple times throughout the lifecycle of an activity.
3> foreground Lifecycle
Start with onresume () and end with onpause. It is in the state of interacting with the user. Of course, the activity will be called back multiple times within the lifecycle of the activity.

-Oncreate (bundle)
Called at the first creation. Generally, static Initialization is completed here. Sometimes with parameters, it stores the frozen state of the last destruction.
Onstart () follows this method and is called back.

-Onretart ()
It is called back from the stop status to the activity status.
Onstart () follows this method and is called back.

-Onstart ()
It is called back when it is visible to the user.
If the user focus is obtained, it is followed by an onresume (); if it becomes invisible, it is followed by an onstop ().

-Onresume ()
Callback when the user focus is obtained. Followed by onpause ().

-Onpause ()
Callback when the system returns to the previous activity.
It generally saves user data and stops animation and other CPU-consuming work. Because only when this method exits will it actually enter the next activity.

-Onstop ()
Callback when the user is invisible. A new activity is created, or a previous activity gets its focus again.

-Ondestroy ()
Resources can be released once before the activity is destroyed. In either case, this method is called: 1> someone calls the finish () method 2> the system memory is tight.
You can use the isfinishing () method to distinguish them.
This method cannot be used to save data! Data should be stored in onpause () or onsaveinstancestate (bundle. Ondestroy () is only applicable to the release of resources such as threads, so as to ensure that nothing is left to the running application after the activity is killed.
Sometimes the system will forcibly kill the activity without calling back this method.

-Onlowmemory ()
The system calls back this method when the memory is tight, but the call time is not exactly defined. In general, the system will first shut down all background processes, and finally kill the main process as the process master and foreground UI. This function is called back before the main process is killed.
This method can be implemented to actively respond to low-memory alarms and actively release resources. The system automatically calls GC after this method.

-Onrestoreinstancestate (bundle)
When the activity is reinitialized from the previously saved status, this method is called back after onstart.
Most applications will be restored in oncreate (bundle), but sometimes some work is easier here. For example, you can directly call the default implementation to restore the frozen view State in onsaveinstancestate (bundle.

-Onsaveinstancestate (bundle)
Save the status of the instance before the activity is killed. The saved items are used in oncreate () or onrestoreinstancestate.
For example, Activity B is created, and activity A is pushed into the stack. Then a may be killed. You can store the UI-related status before being killed and restore the status when the user returns to.
Do not confuse onpause () with onstop. Onpause () has a high probability of being called back. onstop () is called back before being destroyed.
For example, if a user returns from B to A, the onsaveinstancestate () of B is not called, and only onpause () and onstop () are called (). Because B will not be restored.
For example, B is created, and a is pressed to the stack. If a is not killed during the lifecycle of B, the onsaveinstancestate () of A is not called and only onpause () is called ().

Before onstop. It is irrelevant to the front and back of onpause.

If a "configuration change" event occurs on a device (for example, a language change, a device input, or orientation change ), all UIS should re-read resources, layout, text and other data from the configuration file, and then re-establish the UI to present it to the user.
This will cause a series of activity status changes: onpause ()-> onstop ()-> ondestroy ()-> oncreate ()-> onresume ()... that is, the whole activity is rebuilt.
To ignore an event, you must configure the Android: configchanges attribute in androidmanifest. xml. (At the same time, implement the onconfigurationchanged (configuration) method ).

New activities started with startactivity (intent) will be placed at the top of the activity stack. The intent parameter describes the activity to be started.

You can call startactivityforresult (intent, INT) to obtain a return value when an activity ends ). The returned value is obtained in onactivityresult (INT, Int, intent) of the host activity.
The host activity must call setresult (INT) before the end ). You can also append an intent as the additional data.

If the host activity does not end normally (such as a crash), the host will only get a result_canceled returned value.

Public class myactivity extends activity {... static final int pick_contact_request = 0; protected Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_dpad_center) {startactivityforresult (new intent (intent. action_pick, // The user wants to select a contact new uri ("content: // contacts"), // the contact list pick_contact_request); // The Custom activity idreturn true ;} return false;} protected void onactivityresult (INT requestcode, int resultcode, intent data) {If (requestcode = pick_contact_request) {If (resultcode = result_ OK) {// display the returned contact to the user startactivity (new intent (intent. action_view, data ));}}}}

Activity can save data in two ways.
-Shared document-type data (stored in SQLite database );
-Internal private data, such as user preferences ).

For the first storage solution, we recommend that you use the "instant encoding and storage" mode. There are two key points:
-Create an entry in the background database immediately when creating a new document. For example, if you want to edit a new email, create a new entry in the database immediately. In this way, the email is automatically saved to the draft box when the user runs to other activities.
-When the onpause () callback of the activity is performed, it is saved immediately. This ensures that data can be viewed by other running activities.
This means that when you press back, it is not cancel, but save.

Solution 2: Use the getpreferences (INT) method to save the "key-Value Pair" to the storage area corresponding to the activity.
Note: different packages cannot access the internal data. Different activities of the same package can access each other.

public class CalendarActivity extends Activity {...static final int DAY_VIEW_MODE = 0;static final int WEEK_VIEW_MODE = 1;private SharedPreferences mPrefs;private int mCurViewMode;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);}protected void onPause() {super.onPause();SharedPreferences.Editor ed = mPrefs.edit();ed.putInt("view_mode", mCurViewMode);ed.commit();}}

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.