Four components of Android four basic components (3) Summary

Source: Internet
Author: User

A summary of the four basic components:

1> Registration of 4 major components

4 basic components need to be registered to use, each activity, service, Content Provider content providers need to be configured in the Androidmanifest file androidmanifest activity, services, and content providers that are not declared in the file are not visible to the system and are therefore not available. The registration of the Broadcastreceive broadcast receiver, which is configured in the Androidmanifest file, is dynamically created by the code and registered to the system in the form of a call to Context.registerreceiver (). It is important to note that the broadcast receivers configured in the Androidmanifest file will be active as soon as the system is started, as long as the received broadcast is triggered (even if the program is not running)

The registration format in the Androidmanifest file is as follows:

The name attribute of the element specifies the subclass of the activity that implements the activity. The icon and label properties point to the resource file that contains the icons and labels for this activity that are presented to the user.

element is used to declare a service

element is used to declare a broadcast sink

element is used to declare the content provider

2> 4 activation of large components

? The content provider is activated when it receives a request from the Contentresolver. The other three components ──activity, service, and broadcast receivers are activated by an asynchronous message called intent

? Activity is activated by passing an intent object to context.startactivity () or Activity.startactivityforresult () to load (or designate a new job to) an activity. The corresponding activity can view the intent that activates it by calling the Getintent () method. If it expects the activity it initiates to return a result, it will replace startactivity () with the call to Startactivityforresult (). For example, if it launches another activity to allow the user to pick a photo, it may want to know which photo is selected. The result is encapsulated in a intent object and passed to the Onactivityresult () method of the activity that made the call.

? The activation of the service can be done by passing an intent object to Context.startservice () or Context.bindservice () the former Android invoke service's OnStart () method and passing the intent object to it, The latter Android invokes the service's Onbind () method to pass the intent object to it

? Sending a broadcast can be done by passing a intent object to Context.sendbroadcast (),

Context.sendorderedbroadcast () or context.sendstickybroadcast () Android calls all broadcast receivers that are interested in this broadcast OnReceive () method, which will intent Passed to them

3> Closure of four components

The content provider is only activated when responding to contentresolver requests. A broadcast receiver is activated only when it responds to broadcast information. Therefore, it is not necessary to explicitly close these components.

Activity close: You can close an activity by calling its finish () method

Service shutdown: For services started by the StartService () method, to invoke the Context.stopservice () method to close the service, the service started with the Bindservice () method to invoke Contex.unbindservice () method to close the service

2:4 the life cycle of large components

 介绍生命周期之前,先提一下任务的概念

The task is actually a stack of activity. It is composed of one or more activity to complete a complete user experience, in other words, the task is "application" (can be one or more, for example, suppose you want to let users see a street map of a place.) There is already an activity with this function, and the work you need to do is put the request information into a intent object and pass it to StartActivity (). The map browser will then show the map. And when the user presses the Back button, your activity will again appear on the screen, when the task is composed of 2 applications of related activity is the bottom of the activity to start the entire task, the top of the stack is the current user can interact with the activity , when one activity launches another, the new activity is pushed into the stack and becomes the activity currently running. The previous activity remains in the stack. When the user presses the back key, the current activity is out of the stack, and the previous one reverts to the currently running activity. The stack is actually an object, the activity in the stack will never reflow, will only press in or eject, so if a situation such as the need for more than one map browser, it will cause a task to appear multiple instances of the same activity subclass exist simultaneously.

All activity in the task is moved as a whole. The entire task (that is, the activity stack) can be moved to the foreground or back to the background. For example, for example, the current task has four activity── in the stack, three under the current activity. When the user presses the home key, it goes back to the application loader and selects a new application (that is, a new task). The current task is in the background and the root activity of the new task is displayed. Then, after a little while, the user returns to the application loader again and selects the previous application (the previous task). So the task, with all the four activity in the stack, once again to the front desk. When the user presses the back key, the screen does not show the activity that the user has just left (the root of the previous task

Activity). Instead, the topmost activity in the current task's stack pops up, and the last activity in the same task is displayed.

Activity stack: Advanced post-out rules

The Android system is a multitasking (multi-task) operating system that allows you to listen to music on your phone while performing several other programs. With each application, it consumes more system memory, and when too many programs are executed at the same time, or the closed program does not release the memory correctly, the system will feel slower and even more unstable.

To solve this problem, Android introduced a new mechanism – the Lifecycle (life cycle).

The life cycle of Android apps is managed by the Android framework, rather than by the application's direct control

System. Typically, each application (the portal is typically an activity-oncreate method), will produce

a process. When the system memory is about to be insufficient, the process is automatically recycled according to the priority level. No user or developer can determine when the application will be recycled. So in order to prevent data loss and other problems well, it is important to understand the lifecycle.

Activity life cycle:

Figure 3.1activity Life cycle diagram

Activity 4 states, 7 important methods, and 3 nested loops throughout the life cycle

1> of four states

  活动(Active/Running)状态

When the activity is running on the screen foreground (at the top of the current task's activity stack), it gets the focus to respond to the user's action, which is running, and only one moment of activity is active (active) or running

(Running) Status

暂停(Paused)状态

It is paused when the activity loses focus but remains visible to the user (such as when there is another transparent activity or toast, alertdialog, etc.) on top of it. Paused activity is still alive (it retains all state and member information and remains connected to the window manager), but can be killed by the system when the system memory is very small

    1. Stop (Stopped) state

Is in a stopped state when it is completely obscured by another activity, and it retains all the state and member information. It is not visible to the user, but it is often killed by the system when memory is needed elsewhere

    1. Non-active (Dead) status

If the activity has not been started, has been manually terminated, or has been inactive while the system is being reclaimed, you can invoke the "Finish" method in the program to terminate the activity manually.

If it is being reclaimed by the system (according to the recycling rules based on low memory), it may be because there is not enough memory

When memory is low, the Dalvak virtual opportunity reclaims memory according to its memory recycling rules:

  1. 先回收与其他Activity 或Service/Intent Receiver 无关的进程(即优先回收独

activity) It is recommended that some of our (time-consuming) background operations, preferably in the form of service

  2.不可见(处于Stopped状态的)Activity  3.Service进程(除非真的没有内存可用时会被销毁)  4.非活动的可见的(Paused状态的)Activity  5.当前正在运行(Active/Running状态的)Activity

2> 7 Important methods, when the activity from one state into another state, the system will automatically call the following corresponding party

To inform users of this change

When the activity is instantiated for the first time, the system calls,

This method is called only 1 times throughout the life cycle

Typically used to initialize settings: 1, set the layout file to use for the activity 2, the button binding listener and other static settings operations

  onCreate(Bundle savedInstanceState);

When the activity is visible and the user focus does not get interactive, the system calls

  onStart();

When activity is stopped and then restarted, the system calls

  onRestart();

When activity is visible and the user's focus can interact, the system calls

  onResume();

When the system launches another new activity, it must be implemented very quickly by the system call to save the persisted data in the existing activity, stop the animation, etc. before the new activity starts. After the activity has been closed by the system instead of the user's own recovery memory. The user expects that when he returns to the activity again, it remains the way it was when he left. Using Onsaveinstancestate (), the Method Onsaveinstancestate () is used to save the state before the activity is killed, triggered before OnPause (), when the system destroys the activity in order to save memory ( The user does not want to destroy this method, when the activity is instantiated again by OnCreate (Bundle savedinstancestate) will have saved temporary state data passed in because Onsaveinstancestate ( The method is not always called, the trigger condition is (press the Home key, press the power button to turn off the screen, and in both cases), you should only rewrite Onsaveinstancestate () to record the temporary state of activity, rather than persistent data. You should use OnPause () to store persistent data.

  onPause();

Called by the system when the activity is completely overwritten by the new activity is not visible

  onStop();

When the activity (user calls finish () or the system is destroyed by the system due to low memory) the system is called, (the entire life cycle is called only 1 times) to release the resources created in the OnCreate () method, such as the end thread, etc.

  onDestroy();

3> 3 Nested Loops

         1.Activity完整的生命周期:从第一次调用onCreate()开始直到调用onDestroy()结束         2.Activity的可视生命周期:从调用onStart()到相应的调用onStop()                在这两个方法之间,可以保持显示Activity所需要的资源。如在onStart()中注册一个广播接收者监听影响你的UI的改变,在onStop() 中注销。         3.Activity的前台生命周期:从调用onResume()到相应的调用onPause()。  举例说明:

Example 1: There are 3 acitivity, respectively, with one,two (Transparent), three that one is the main activity when the application starts

  启动第一个界面Activity One时,它的次序是         onCreate (ONE) - onStart (ONE) - onResume(ONE)  点"打开透明Activity"按钮时,这时走的次序是         onPause(ONE) - onCreate(TWO) - onStart(TWO) - onResume(TWO)  再点back回到第一个界面,Two会被杀这时走的次序是         onPause(TWO) - onActivityResult(ONE) - onResume(ONE) - onStop(TWO) - onDestroy(TWO)  点"打开全屏Activity"按钮时,这时走的次序是         onPause(ONE) - onCreate(Three) - onStart(Three) - onResume(Three) - onStop(ONE)  再点back回到第一个界面,Three会被杀这时走的次序是         onPause(Three) - onActivityResult(ONE) - onRestart(ONE) - onStart(ONE)- onResume(ONE) - onStop(Three) - onDestroy(Three)  再点back退出应用时,它的次序是         onPause(ONE) - onStop(ONE) - onDestroy(ONE)           

Example 2: The life cycle of the activity when the screen is switched

What is the specific life cycle when he switches:

1. Create a new activity and print out each life cycle

2, run the activity, get the following information

Oncreate–>
Onstart–>
Onresume–>

3, press CRTL+F12 switch Cheng

Onsaveinstancestate–>
Onpause–>
Onstop–>
Ondestroy–>
Oncreate–>
Onstart–>
Onrestoreinstancestate–>
Onresume–>

4, and then press CRTL+F12 to switch to vertical screen, found that two times the same log was printed

Onsaveinstancestate–>
Onpause–>
Onstop–>
Ondestroy–>
Oncreate–>
Onstart–>
Onrestoreinstancestate–>
Onresume–>
Onsaveinstancestate–>
Onpause–>
Onstop–>
Ondestroy–>
Oncreate–>
Onstart–>
Onrestoreinstancestate–>
Onresume–>

5, modify the Androidmanifest.xml, add the activity android:configchanges= "orientation", perform step 3

Onsaveinstancestate–>
Onpause–>
Onstop–>
Ondestroy–>
Oncreate–>
Onstart–>
Onrestoreinstancestate–>
Onresume–>

6, then perform step 4, found that the same information will not be printed, but more than print a line onconfigchanged

Onsaveinstancestate–>
Onpause–>
Onstop–>
Ondestroy–>
Oncreate–>
Onstart–>
Onrestoreinstancestate–>
Onresume–>
Onconfigurationchanged–>

7, change step 5 android:configchanges= "orientation" to android:configchanges= "Orientation|keyboardhidden", perform step 3, Just print onconfigchanged

Onconfigurationchanged–>

8. Perform step 4

Onconfigurationchanged–>
Onconfigurationchanged–>

Summarize:

1, do not set the activity of the android:configchanges, the screen will recall the various life cycle, cut across the screen will be executed once, cut the vertical screen will be executed twice

2, set the activity android:configchanges= "orientation", the screen will recall the various life cycle, cut horizontal, vertical screen will only be executed once

3, set the activity android:configchanges= "Orientation|keyboardhidden", the screen will not recall the various life cycle, will only execute onconfigurationchanged method

Summarize the life cycle of the activity

To add, the activity's life cycle will not change when the current activity generates an event that pops up toast and alertdialog

The activity runtime presses the home key (the same as when it is fully overwritten):onsaveinstancestate–> onpause–> OnStop, once again into the active state: onrestart–>onstart-> Onresume

Broadcastreceive Broadcast receiver life cycle:

The life cycle is only about 10 seconds, if within onreceive () do more than 10 seconds of things, will report the ANR (Application no Response) program unresponsive error message

Its life cycle ends when the callback OnReceive () method starts and the method returns results

Service life cycle:

Figure 3.2service Life cycle diagram

Service Complete life cycle: from calling OnCreate () until the call OnDestroy () ends

There are two ways to use the service:

1> starts with call Context.startservice (), and ends with a call to Context.stopservice ()

2> is established to call the Context.bindservice () method to invoke Context.unbindservice () to close

Service-critical life cycle approach

When the user calls StartService () or Bindservice (), the first time the service is instantiated, the system invokes the method, which is called only 1 times throughout the life cycle, and is typically used to initialize the settings. Note: Calling the StartService () or Bindservice () method multiple times does not trigger the OnCreate () method multiple times

void OnCreate ()
Called by the system when the user calls StopService () or Unbindservice () to stop the service (the entire life cycle is called only 1 times) to release the resources created in the OnCreate () method

void OnDestroy ()
Services initiated through the StartService () method

  初始化结束后系统会调用该方法,用于处理传递给startService()的Intent对象。如音乐服务会打开Intent 来探明将要播放哪首音乐,并开始播放。注意:多次调用startService()方法会多次触发onStart()方法

void OnStart (Intent Intent)
Services initiated through the Bindservice () method

  初始化结束后系统会调用该方法,用来绑定传递给bindService 的Intent 的对象。注意:多次调用bindService()时,如果该服务已启动则不会再触发此方法

IBinder Onbind (Intent Intent)
The system calls this method when the user calls Unbindservice (), and the Intent object is also passed to the method

Boolean onunbind (Intent Intent)
If a new client connects to the service, the new one will only call the method after the old call Onunbind ()

void Onrebind (Intent Intent)
Add: OnCreate (Bundle savedinstancestate) in conjunction with Onsaveinstancestate (bundle savedinstancestate), see the following code, To show the state before the activity was killed by the system.

Copy Code
@Override
public void onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate); if (null! = savedinstancestate) {
String _userid = savedinstancestate.getstring ("strUserID");
String _uid = savedinstancestate.getstring ("Struid");
String _serverid = savedinstancestate.getstring ("Strserverid");
String _servername = savedinstancestate.getstring ("strServerName");
int _rate = Savedinstancestate.getint ("Strrate");
//updateuserid (_userid);
//updateuid (_UID);
//updateserverid (_serverid);
//updateuserserver (_servername);
//updaterate (_rate);
}
}

@Overrideprotected void onSaveInstanceState(Bundle savedInstanceState) {    super.onSaveInstanceState(savedInstanceState);    savedInstanceState.putString("StrUserId", getUserId());    savedInstanceState.putString("StrUid", getUId());    savedInstanceState.putString("StrServerId", getServerId());    savedInstanceState.putString("StrServerName", getServerName());    savedInstanceState.putInt("StrRate", getRate());}

Copy Code

Other situations that trigger activity destruction and reconstruction

In addition to the fact that the system is out of memory to destroy activity, changes in some system settings can cause activity to be destroyed and rebuilt. For example, change the screen orientation (see the example above), Change device language settings, keyboard popup, etc.

Four components of Android four basic components (3) Summary

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.