The four components of Android development are activity, service, broadcast receiver, and content provider. As an amateur developer, you may not need to understand the internal implementation of these components too deeply, as well as the operating mechanism. But if you want to be in this aspect, the source of these implementations is still to be chewed. This article will explain the activity from the official source.
Overview
Defined
The official start of activity is described as:
/**an activity is a single, focused thing this user can do. Almost all activities interact with the user, and the Activity class takes care of creating a window for you in which C An the Your UI with Setcontentview (int). While activities is often presented to the user as Full-screen windows, they can also is used in other ways:as floating Windows (via a theme with Android. R.attr set) or embedded inside of another activity (using Activitygroup). There is, methods almost all subclasses of Activity would implement:oncreate (Android.os.Bundle) is where you Initia Lize your activity. Most importantly, where you'll usually call Setcontentview (int.) with a layout resource defining your UI, and using fi Ndviewbyid (int) to retrieve the widgets in so UI that's need to interact with programmatically. OnPause () is a where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point is committed (usually toThe android.content.ContentProvider holding the data). **/
From the four components of Android, activity is the only component that can interact with the user, so activity can create a window and set the window's UI by calling Setcontentview (int).
Moreover, activity is not limited to occupying the entire screen, it can be a hover window or be embedded in other activity.
Activity status
Then look at a acitivity life cycle, although there are many explanations of the activity life cycle on the internet, but still paste the source notes:
/**activities in the system is managed as an activity stack. When a new activity is started, it's placed on the top of the stack and becomes the running activity-the previous ACTI Vity always remains below it in the stack, and won't come to the foreground again until the new activity exits. An activity had essentially four states:1.if a activity in the foreground of the the the the stack, it is active or running. 2.If an activity had lost focus but was still visible (that's, a new non-full-sized or transparent activity has Focus on top of the Your activity), it is paused. A paused activity is completely alive (it maintains all, and member information and remains attached to the win Dow manager), but can is killed by the system in extreme low memory situations. 3.If an activity was completely obscured by another activity, it was stopped. It still retains all state and member information, however, it's no longer visible toThe user so's window is hidden and it'll often be killed by the system when memory is needed elsewhere. 4.If an activity was paused or stopped, the system can drop the activity from memory by either asking it to finish, O R simply killing its process. When it was displayed again to the user, it must was completely restarted and restored to its previous state.**/
As you can see from the explanation, the system manages the activity in the form of a stack, and when a new activity starts, it will be at the top of the stack (top of the stack) and become running activity.
There are four states for an activity, namely:
1.Active or running, when the activity is in the foreground, which is the front of the screen.
2.Paused, when the activity loses focus but is still visible, the typical case is that a warning box pops up to the front of the screen. In this state, the activity loses focus and the user's interaction is not acceptable. When the system is in extreme lack of memory, the activity can still be killed by the system.
3.Stopped when the activity is completely invisible.
4.killed or recovery, an activity in paused or stopped state, the system can choose to reclaim the activity's memory, and then kill the activity, or before the system is recycled, the user re-bring the activity to the foreground, And then recovered it. Be aware that this choice of system is not subject to human intervention, so development should always be aware of the circumstances of activity being killed.
Life cycle Type
The note also divides the activity's life cycle by features into several types:
/** 1.The entire lifetime of an activity happens between the first call to OnCreate (Android.os.Bundle) through to A single final call to OnDestroy (). An activity would do all setup of ' global ' state in OnCreate (), and release all remaining resources in OnDestroy (). For example, if it had a thread running in the background to download data from the network, it may create tha T thread in OnCreate () and then stop the thread in OnDestroy (). 2.The visible lifetime of an activity happens between a call to OnStart () until a corresponding call to OnStop (). During this time the user can see the activity on-screen, though it may isn't is in the foreground and interacting wit H the user. Between these, methods you can maintain resources, is needed to show the activity to the user. For example, you can register a android.content.BroadcastReceiver in OnStart () to monitor for changes that impact yo ur UI, and unregister it in OnStop () when theUser no longer sees what is displaying. The OnStart () and OnStop () methods can be called multiple times, as the activity becomes visible and hidden to the user. 3.The foreground lifetime of an activity happens between a call to Onresume () until a corresponding call to OnPause (). During this time, the activity is in front of any other activities, and interacting with the user. An activity can frequently go between the resumed and paused states--for example when the device goes to sleep, wh En an activity result was delivered, when a new intent was delivered--the code in these methods should was fairly Lightweight. **/
1. Full life cycle (entire lifetime), from an activity that is created to allocate memory to memory that is reclaimed by the system.
2. The visual life cycle (visible lifetime), the time between OnStart () and OnStop (), can be seen by the user.
3. The foreground life cycle (Foregroud lifetime), the time between Onresume () and OnPause (), can be seen and interacted with by the user.
Through the above explanations, it is not difficult to see the activity life cycle charts that are ubiquitous online.
Look at the life cycle Chart, compare the official notes, and look at the source of each callback function
callback function OnCreate
/**called when the activity is starting. This is where most initialization should go:calling Setcontentview (int.) to inflate the activity ' s UI, using Findviewbyid ( int) to programmatically interact with widgets in the UI, calling Managedquery (android.net.uri,java.lang.string[], java.lang.string,java.lang.string[],java.lang.string) to retrieve cursors for data being displayed, etc. You can call finish () from within this function, in which case OnDestroy () 'll be immediately called without any of the R EST of the Activity Lifecycle (OnStart (), Onresume (), OnPause (), etc) executing. Derived classes must call through to the Super class ' s implementation of this method. If They does not, an exception would be thrown. Parameters:savedinstancestate If The activity is being re-initialized after previously being shut and then this B Undle contains the data it most recently supplied in Onsaveinstancestate (android.os.Bundle). Note:otherwise It is null.**/protected void onCreate (@NullableBundle savedinstancestate) {if (debug_lifecycle) slog.v (TAG, "onCreate" + This + ":" + savedinstancestate); if (mlastnonconfigurationinstances! = null) {mallloadermanagers = Mlastnonconfigurationinstances.loader S if (mactivityinfo.parentactivityname! = null) {if (Mactionbar = = null) {Menabledef Aultactionbarup = true; } else {mactionbar.setdefaultdisplayhomeasupenabled (true); }} if (savedinstancestate! = null) {parcelable p = savedinstancestate.getparcelable (FRAGMENT S_tag); Mfragments.restoreallstate (p, mlastnonconfigurationinstances! = null? mlastnonconfigurationinstances. Fragments:null); } mfragments.dispatchcreate (); Getapplication (). dispatchactivitycreated (this, savedinstancestate); if (mvoiceinteractor! = null) {mvoiceinteractor.attachactivity (this); } mcalled = true; }When an activity is created, the system will callback the activity's OnCreate () method, but it is not clear that the method creates an activity. From the source view, the system calls the method, mainly to do some of the activity of the state variable modification. In order to preserve the consistency of the system Management Acitivity, the developer is required to invoke the parent class method when overriding the method. When an activity instance is created, the system only calls the method once, so the method is suitable for creating views, bind data to lists and so on. Note that the nullable bundle class parameter of this method Savedinstancestate, the system will automatically join the parameter call only after the system configuration has been modified and the system needs to quickly kill the activity and recreate it to fit the system environment. It holds the user interaction before the activity is destroyed. A typical situation where the device is set up a horizontal screen, if the user entered some characters in an input box, and then a spin event, because the current activity is built on the vertical screen, it is not suitable for horizontal screen, So the system needs to destroy the current activity and re-create a new activity according to the horizontal screen standard. However, due to the user input, the system should not be lost in the process of destroying-rebuilding the user's input state before the turn-on screen, so the system will pass the information into the bundle before destroying the activity, and then add the bundle to restore the input state when rebuilding.
OnStart
/**called after OnCreate (android.os.Bundle)-or after Onrestart () while the activity had been stopped, but was now again be ing displayed to the user. It is followed by Onresume (). Derived classes must call through to the Super class ' s implementation of this method. If they does not, an exception would be thrown.**/ protected void OnStart () { if (debug_lifecycle) slog.v (TAG, "Onsta RT "+ this); Mcalled = true; if (!mloadersstarted) { mloadersstarted = true; if (Mloadermanager! = null) { mloadermanager.dostart (); } else if (!mcheckedforloadermanager) { Mloadermanager = Getloadermanager ("(Root)", mloadersstarted, False); } Mcheckedforloadermanager = true; } Getapplication (). dispatchactivitystarted (this); }
When activity is present in the foreground, in other words, the system will call the method after rendering the UI. The internal implementation is the modification of some state variables, called the lower function.
Onresume
/**called after Onrestoreinstancestate (Android.os.Bundle), Onrestart (), or onPause (), for your activity to start interact ing with the user. This was a good place to begin animations, open exclusive-access devices (such as the camera), etc. Keep in mind that Onresume are not the best indicator that your activity is visible to the user; A system window such as the Keyguard May is in front. Use Onwindowfocuschanged (Boolean) to know for certain that your activity are visible to the user (for example, to resume a Game). Derived classes must call through to the Super class ' s implementation of this method. If they does not, an exception would be thrown.**/ protected void Onresume () { if (debug_lifecycle) slog.v (TAG, "onre Sume "+ this); Getapplication (). dispatchactivityresumed (this); Mactivitytransitionstate.onresume (); Mcalled = true; }
The system calls this method when activity can begin interacting with the user. It is not the time to call OnStart () when the UI is finished rendering the listener function, so the user is not interactive, then call OnStart (). The system calls the Onresume () function when the user taps the screen to get an interaction when the listener function is bound at each location on the screen. This explains why the activity's life cycle is only onpause () and Onresume () When a warning box is suspended or disappearing from activity, because the activity is visible, and it simply loses the binding of the screen to the listener function. So when the warning box disappears, the UI does not need to be redrawn, it only needs to be able to rebind the screen with the listener function, so OnStart () is not called. If the activity exits the foreground, it needs to go through the rendering of the UI before returning to the foreground, so OnStart () is called at this point.
OnPause
/**called as part of the activity lifecycle if an activity was going into the background, but had not (yet) been killed. The counterpart to Onresume (). When activity B was launched in front of activity A, the this callback would be being invoked on a. B would not being created until A ' s on Pause () returns, so is sure to does anything lengthy here. This callback was mostly used for saving all persistent state the activity was editing,to present a "edit in place" model to The user and making sure is lost if there be not enough resources to start the new activity without first Killin G this one. This is also a good place to does things like stop animations and other things that consume a noticeable amount of CPUs in or Der to do the switch to the next activity as fast as possible, or to close resources that is exclusive access such as T He camera. In situations where the system needs more memory it could kill paused processes to reclaim resources. Because of this, you should is sure that all of your statE is saved by the time you return from this function. In general Onsaveinstancestate (Android.os.Bundle) was used to save per-instance state in the activity and this method is us Ed to store global persistent data (in content providers, files, etc.) After receiving this call, you'll usually receive a following call to OnStop () (after the next activity have been res Umed and displayed), however in some cases there would be a direct call back to Onresume () without going through the Stoppe D state. Derived classes must call through to the Super class ' s implementation of this method. If they does not, an exception would be thrown.**/protected void OnPause () {if (debug_lifecycle) slog.v (TAG, "OnP Ause "+ this); Getapplication (). dispatchactivitypaused (this); Mcalled = true; }The system calls this method when an activity leaves the foreground before entering the background. It is important to note that the background (background) of activity entry can be understood simply as the activity becomes non-interactive. According to the system definition, an activity may be killed off at any time after the system calls OnPause (), so any state or information that needs to be saved needs to be stored in this function. Time-consuming operations should not be done in OnPause () because other activity cannot be displayed until OnPause () is finished.
/**called when is no longer visible to the user. You'll next receive either Onrestart (), OnDestroy (), or nothing, and depending on later user activity. Note that this method may never is called, in low memory situations where the system does not has enough memory to keep y Our activity's process running after it OnPause () method is called. Derived classes must call through to the Super class ' s implementation of this method. If they does not, an exception would be thrown.**/ protected void OnStop () { if (debug_lifecycle) slog.v (TAG, "onStop "+ this); if (Mactionbar! = null) mactionbar.setshowhideanimationenabled (false); Mactivitytransitionstate.onstop (); Getapplication (). dispatchactivitystopped (this); Mtranslucentcallback = null; Mcalled = true; }
The system calls this method when the activity is no longer visible. It is important to note that the system does not invoke the method when it needs to kill the activity to obtain more memory.
OnStop
/**called after OnStop (), the current activity was being re-displayed to the user (the user had navigated back to it). It is followed by OnStart () and then Onresume (). For activities that is using raw android.database.Cursor objects (instead of creating them through Managedquery (ANDROID.N Et. uri,java.lang.string[],java.lang.string,java.lang.string[],java.lang.string) Usually the place where the Cursor should is requeried (because you had deactivated it in OnStop (). Derived classes must call through to the Super class ' s implementation of this method. If They does not, an exception would be thrown.**/ protected void Onrestart () { mcalled = true; }
The system calls this method when the activity is shown again in the foreground.
OnDestroy
/**perform any final cleanup before a activity is destroyed. This can happen either because the activity was finishing (someone called finish () on it, or because the system is Temporar Ily destroying this instance of the activity to save space. You can distinguish between these-scenarios with the Isfinishing () method. Note:do not count on this method being called as a place for saving data! For example, if the activity is editing data in a content provider, those edits should being committed in either onPause () or Onsaveinstancestate (Android.os.Bundle), not here. This method was usually implemented to the free resources like threads that's associated with an activity, so that a Destroye D activity does not leave such things around while the rest of their application is still running. There is situations where the system would simply kill the activity ' s hosting process without calling this method (or any Others) in it, so it should not being used to does things that is intended to remain around aftEr the process goes away. Derived classes must call through to the Super class ' s implementation of this method. If they does not, an exception would be thrown.**/protected void OnDestroy () {if (debug_lifecycle) slog.v (TAG, "O Ndestroy "+ this); Mcalled = true; Dismiss any dialogs we is managing. if (mmanageddialogs! = null) {final int numdialogs = Mmanageddialogs.size (); for (int i = 0; i < numdialogs; i++) {final Manageddialog MD = mmanageddialogs.valueat (i); if (md.mDialog.isShowing ()) {Md.mDialog.dismiss (); }} mmanageddialogs = null; }//Close any cursors we is managing. Synchronized (mmanagedcursors) {int numcursors = Mmanagedcursors.size (); for (int i = 0; i < numcursors; i++) {Managedcursor c = mmanagedcursors.get (i); if (c! = null) {c.Mcursor.close (); }} mmanagedcursors.clear (); }//Close any open Search dialog if (Msearchmanager! = null) {Msearchmanager.stopsearch (); } getapplication (). dispatchactivitydestroyed (this); }The system calls this method after the activity calls finish () or when the system needs to destroy the activity. Note that the system can still choose not to call the method and destroy the activity directly.
Summarize:
The callback function of the 1.Activity life cycle is called before and after the next operation for the developer to implement some operations before and after each stage.
2. The implementation of some callback functions is simple, but it is an important operation to get through an activity life cycle. So in order to maintain the consistency of the activity and avoid the developer's understanding of the whole lifecycle principle, Android enforces the need to invoke the parent class when overriding these callback functions;
The lifetime of the 3.Activity OnCreate () is only called once, it needs to fit a global variable assignment, the Listener function is set, and OnStart () and Onresume () may be called multiple times, so it is not appropriate to create an object in the method, because it is called once, The previous object was garbage. More rubbish, the program is not a good thing for the system;
4. In some cases, the system can kill the activity directly over OnStop () and OnDestroy (), so the preservation of some important information should be placed in the OnPause ();
The principle of 5.Activity is that the system calls the various callback functions, the developer cannot control the life cycle of an activity, but can customize some implementation in its life cycle, so that it can run according to the general definition;
5. There are many functions that can be found in the activity, and the maximum procedure is to ensure that a project can be implemented by the activity, which indicates how ingenious and meticulous a system is. A onkeydown () callback function, for example, is used to monitor the input situation of a user. But the monitoring of the key is also a system behavior, it will follow the transfer level of the input situation down, if the input is processed in a certain layer, return true to indicate that the system will no longer pass the input situation, return False indicates that the layer is not processed, the system can continue to pass down. Wait a minute.
Learn to organize--see activity from Android source code