Active/RuningAfter a new Activity is started into the stack, it is at the front end of the screen and at the top of the stack. At this time, it is visible and can interact with users.PausedThe status when the Activity is overwritten by another transparent or Dialog style Activity. At this time, it is still connected to the window manager, and the system continues to maintain its internal status, so it is still visible, but it has lost its focus, so it cannot interact with users.StopedWhen the Activity is overwritten by another Activity and the focus is not visible StopedStatus.KilledWhen the Activity is killed or recycled by the system or is not startedKilledStatus.When an Activity instance is created, destroyed, or started, it is converted between the four States. This conversion relies on the action of the user program. The time and conditions for Activity switching between different States are described:
Figure 1. Activity Status transition
As shown above, the Android programmer can determine the "life" of an Activity, but cannot determine its "death". That is to say, the programmer can start an Activity, however, you cannot manually "end" an Activity. When you callActivity. finish ()Method, the result is the same as pressing the BACK key: Tell Activity Manager that the Activity instance has completed the corresponding work and can be "recycled ". Then the Activity Manager activates the Activity at the second layer of the stack and re-enters the stack. At the same time, the original Activity is pushed to the second layer of the stack, and changes from Active to Paused. For example, if Activity2 is started from Activity1, Activity2 is currently at the top of the stack, and Activity1 is the second layer. When we callActivity2.finish ()Method, Activity Manager re-activates Activity1 to merge into the stack, and Activity2 changes from Active to Stoped,Activity1. onActivityResult (int requestCode, int resultCode, Intent data)The method is executed, and the data returned by Activity2 isDataThe parameter is returned to Activity1.
Activity Stack
Android manages an Activity through an Activity stack. The status of an Activity Instance determines its position in the stack. The front-end Activity is always at the top of the stack. When the current Activity is destroyed due to exceptions or other reasons, the Activity on the second layer of the stack will be activated and go up to the top of the stack. When a new Activity is started into the stack, the original Activity is pushed to the second layer of the stack. The change in the position of an Activity in the stack reflects its transition between different States. Shows the relationship between the Activity status and its position in the stack:
Figure 2. Relationship between the Activity status and its position in the stackAs shown above, except for the Activity in the Active state at the top layer, other activities may be recycled when the system memory is insufficient. The more an Activity instance is at the bottom layer of the stack, it is more likely to be recycled by the system. The system is responsible for managing the instances of the Activity in the stack. It changes its position in the stack according to the Activity status.
The Activity lifecycle isAndroid. app. ActivityClass, Android defines a series of lifecycle-related methods. In our own Activity, we only need to rewrite the required methods as needed.
Activity lifecycle diagram:
The following describes the lifecycle of an Activity through an instance. Create a project and write the following code:
public class MainActivity extends AppCompatActivity { private String TAG = MainActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, onCreate); } @Override protected void onResume() { super.onResume(); Log.i(TAG, onResume); } @Override protected void onStart() { super.onStart(); Log.i(TAG, onStart); } @Override protected void onPause() { super.onPause(); Log.i(TAG, onPause); } @Override protected void onStop() { super.onStop(); Log.i(TAG, onStop); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, onRestart); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, onDestroy); }}We can record operations and print logs to see the Activity lifecycle process;
1. Run
See the following print log:
11-26 09:09:33. 665 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onCreate
11-26 09:09:33. 665 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onStart
11-26 09:09:33. 665 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onResume
2. Press the return button:
11-26 09:30:20. 097 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onPause
11-26 09:30:20. 637 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onStop
11-26 09:30:20. 637 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onDestroy
3. Press the Home Key to display the recently opened application. Click ActivityDemo.
11-26 09:31:07. 341 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onCreate
11-26 09:31:07. 341 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onStart
11-26 09:31:07. 341 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onResume
4. Press the Home Key.
11-26 09:31:44. 649 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onPause
11-26 09:31:45. 173 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onStop
5. Click Open in AllList.
11-26 09:32:11. 793 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onRestart
11-26 09:32:11. 793 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onStart
11-26 09:32:11. 793 24933-24933/com. jcdh. jcli. activitydemo I/MainActivity: onResume
We can see through the log information.
Activity startup process: onCreate-onStart-onResume;
When the return key is down: onPause-onStop-onDestroy, as stated above, when the return key is pressed, the Activity pops up the stack and the program is destroyed. Indeed;
When we start the service again, we return to onCreate-onStart-onResume. OK;
After startup, press the Home Key and return to Launcher to view the print information: onPause-onStop;
Re-open the running process: onRestart-onStart-onResume;
Through various operations on the Activity, the lifecycle of the Activity is formed. We can see that no matter what operations are performed on the Activity, the relevant callback method will be received, in the development process, we can use these callback methods to write work, such as releasing heavyweight objects, network connections, database connections, and file reads.
The following describes the methods in detail:
OnCreate (): called when the activity is created for the first time. In this method, you need to complete all normal static settings, such as creating a view and binding list data. If the status of the activity can be captured, the Bundle object passed in by this method will store the current status of the activity. After this method is called, The onStart () method is generally called.
OnRestart (): This method is called when the activity is restarted after it is stopped. The onStart method will be called later.
OnStart () calls this method before the activity is visible to the user. If the activity returns to the foreground, onResume () is called. if the activity is hidden, onStop () is called ()
OnResume (): This method is called before the activity starts to interact with the user. At this time, the activity is at the top of the activity stack and receives user input. The onPause () method will be called later.
OnPause (): This method is called when the system is ready to start resuming other activities. This method is usually used to submit some unsaved changes to persistent data, stop some animations or other CPU-consuming operations. Any operation in this method requires quick completion, because the next activity cannot be restored if it does not return. If the activity is returned to the foreground, onResume () is called. If the activity becomes invisible to the user, onStop () is called ().
OnStop (): This method is called when the activity is invisible to the user. This method may be called because the current activity is being destroyed, or another activity (an existing activity or a new activity) has been restored and is being overwritten. OnRestart will be called later when the activity is preparing to return the interaction with the user, and onDestroy will be called if the activity is being released.
OnDestroy (): This method is called before the activity is destroyed. This is the last call that activity can receive. This method may be called because the finish method is called to disable the current activity, or the system calls this method to protect the memory from temporarily releasing the instance of this activity. You can use the isFinishing method to differentiate the two different situations.
To start another Activity, we can call startActivity to start a new Activity. For example:
Intent intent =new Intent(CurrentActivity.this,OtherActivity.class); startActivity(intent);
Note:OtherActivityAlso defined in AndroidManifest. xml.
Intent communication is used for inter-Activity communication.
In Android, different Activity instances may run in one process or in different processes. Therefore, we need a special mechanism to help us transmit messages between activities. In Android, a message is represented by an Intent object. An Intent object not only contains the destination of the message, but also the content of the message. This is like an Email, which should not only contain the Receiving address, it can also contain specific content. For an Intent object, the message "destination" is required, while the content is optional.
In the preceding exampleActivity. startActivity (intent)When starting another Activity, we specified the "recipient address" in the Intent class constructor ".
We passBundleObject To transmit information,BundleMaintainsHashMap Object, which stores our data in this HashMap for transmission. But the code like above is a little complicated, because Intent has preparedBundleSo we can also use this simpler method:
Intent intent =new Intent(MainActivity.this,OtherActivity.class); intent.putExtra(boolean_key, true); intent.putExtra(string_key, string_value); startActivity(intent);
Receive:
Intent intent=getIntent(); intent.getBooleanExtra(boolean_key,false); intent.getStringExtra(string_key);
The Intent Filterntent Filter of Activity describes the Intent objects that a component is willing to receive. Android abstracts them into the android. content. IntentFilter class. In the AndroidManifest. xml configuration file of Android, you can use The node specifies its Intent Filter for an Activity to tell the system what kind of Intent the Activity can respond.
When a programmer uses startActivity (intent) to start another Activity, if the Component Attribute of the intent object is specified directly, Activity Manager tries to start the Activity specified by its Component attribute. Otherwise, Android finds the most matched startup from all the activities installed in the system using other Intent attributes. If no suitable Activity is found, the application will get an exception thrown by the system. The matching process is as follows:
Figure 4. Matching Process of Intent filters of Activity types
Action matching Action is a user-defined string used to describe an Android Application Component. An Intent Filter can contain multiple actions. When AndroidManifest. xml Activity is defined The node specifies an Action list to indicate the "actions" that the Activity can accept. For example:
If we use this Intent object when starting an Activity:
Intent intent =new Intent(); intent.setAction(com.zy.myaction); |
Then, all actions includeCom. zy. myaction.
Android predefines a series of actions to indicate specific system actions. These actions are defined by constants inAndroid. content. IntentToACTION _. You can find detailed descriptions in the documentation provided by Android.
URI data matching
An Intent can carry external data to the target component through the URI. In In the nodeNodes match external data.
The mimeType attribute specifies the data type that carries external data, scheme specifies the protocol, host, port, path specifies the data location, port, and path. As follows:
If these attributes are specified in the Intent Filter, the URI data match is successful only when all the attributes match successfully.
Category match
The node can define a Category list for the component. If the Intent contains all the items in this list, the Category match will be successful.
Some tips on Activity lock the screen direction during Activity runningAndroid has built-in support for direction sensors. In G1, Android will automatically switch between the portrait screen and landscape Screen Based on the G1 direction. However, sometimes our applications can only run on horizontal or vertical screens, such as some games. At this time, we need to lock the screen direction when the Activity is running,NodeAndroid: screenOrientationProperty to complete this task. The sample code is as follows:
// Portrait screen, landscape screen when the value is landscape ............
Full Screen ActivityTo make an Activity run in full screen, you canOnCreate ()Add the following code in the method:
// Set the full-screen mode getWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN, WindowManager. LayoutParams. FLAG_FULLSCREEN); // remove the title bar requestWindowFeature (Window. FEATURE_NO_TITLE );
Set Activity TitleSetTitle (my );
Double-click the return key to exit:
Private long exitTime = 0; @ Overridepublic boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK & event. getAction () = KeyEvent. ACTION_DOWN) {if (System. currentTimeMillis ()-exitTime)> 2000) {Toast. makeText (getApplicationContext (), and then exit the program once, Toast. LENGTH_SHORT ). show (); exitTime = System. currentTimeMillis ();} else {finish (); System. exit (0);} return true;} return super. onKeyDown (keyCode, event );}