您的位置:首页 > 其它

笔记:Activity生命周期

2016-04-24 13:09 369 查看
总结:1.Activity处于Resumed状态,该状态下用户可以与Activity进行交互(通常也被理解为”running” 状态)

      2.Activity能够长期保持在Resumed,Paused,Stopped这三个状态,Activity获得焦点能与用户交互时处于Resumed状态,Acitivy被其他Activity部分覆盖,则处于Paused状态,被其他Activity完全覆盖则处于Stopped状态,

      3.大部分情况下onDestroy()方法在onPause()方法和onStop()方法被调用后执行,但如果在onCreate()方法中调用finish()则直接调用onDestroy()方法,在极端情况下系统在自动摧毁app时不调用Activity的onDestroy()方法

  4.onPause(),onStop()中适合执行一些关闭消耗cpu行为,释放资源,存储数据的操作,onStop()更适合执行其中比较耗时的操作(比如写数据到数据库),onPause()不适合执行耗时操作,以便更快地跳转到其它Activity或app

  5.当应用遇到意外情况(如:内存不足、用户直接按Home键)由系统销毁一个Activity时,onSaveInstanceState() 会被调用。但是当用户主动去销毁一个Activity时,例如在应用中按返回键,onSaveInstanceState()就不会被调用。因为在这种情况下,用户的行为决定了不需要保存Activity的状态。由于onSaveInstanceState()方法方法不一定会被调用,所以onSaveInstanceState()只适合用于保存一些临时性的状态,而onPause()适合用于数据的持久化保存(比如将数据保存到数据库或文件中)。如果我们没有覆写onSaveInstanceState()方法,
此方法的默认实现会自动保存activity中的某些状态数据, 比如activity中各种UI控件的状态.。在onPause()中不适合用来保存比较费时的数据。

6.onRestoreInstanceState()被调用的前提是,activity“确实”被系统销毁了,而如果仅仅是停留在有这种可能性的情况下,则该方法不会被调用。

During the life of an activity, the system calls a core set of lifecycle methods in a sequence similar to a step pyramid. That is, each stage of the activity lifecycle is a separate step on the pyramid. As the system creates
a new activity instance, each callback method moves the activity state one step toward the top. The top of the pyramid is the point at which the activity is running in the foreground and the user can interact with it.

As the user begins to leave the activity, the system calls other methods that move the activity state back down the
pyramid in order to dismantle the activity. In some cases, the activity will move only part way down the pyramid and wait (such as when the user switches to another app), from which point the activity can move back to the top (if the user returns to the activity)
and resume where the user left off.



Figure 1. A simplified illustration of the Activity lifecycle, expressed as a step pyramid. This shows how, for every callback used to take the activity a step toward the Resumed state at the top, there's a callback
method that takes the activity a step down. The activity can also return to the resumed state from the Paused and Stopped state.

Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Implementing your activity
lifecycle methods properly ensures your app behaves well in several ways, including that it:
Does not crash if the user receives a phone call or switches to another app while using your app.
Does not consume valuable system resources when the user is not actively using it.
Does not lose the user's progress if they leave your app and return to it at a later time.
Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.
能保持长期存在的状态

As you'll learn in the following lessons, there are several situations in which an activity transitions between different states that are illustrated in figure 1.However, only three of these
states can be static. That is, the activity can exist in one of only three states for an extended period of time:
ResumedIn this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)PausedIn this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does
not receive user input and cannot execute any code.StoppedIn this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such
as member variables is retained, but it cannot execute any code.
The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method. That is, after the system calls 
onCreate()
,
it quickly calls
onStart()
, which is quickly followed by 
onResume()
.

Once the 
onCreate()
 finishes
execution, the system calls the 
onStart()
 and 
onResume()
 methods
in quick succession. Your activity never resides in the Created or Started states.Technically, the activity becomes visible to the user when 
onStart()
 is
called, but 
onResume()
 quickly
follows and the activity remains in the Resumed state until something occurs to change that, such as when a phone call is received, the user navigates to another activity, or the device screen turns off.

That's it for the basic activity lifecycle. Now you'll start learning about some of the specific lifecycle behaviors

一些细节:

onCreate()--

You must implement the 
onCreate()
 method
to perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of 
onCreate()
 should
define the user interface and possibly instantiate some class-scope variables.

For example, the following example of the 
onCreate()
 method
shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.

onDestroy()--

Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during 
onPause()
 and 
onStop()
.
However, if your activity includes background threads that you created during 
onCreate()
 or
other long-running resources that could potentially leak memory if not properly closed, you should kill them during 
onDestroy()
.

@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass
   
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}


Note: The system calls 
onDestroy()
 after
it has already called 
onPause()
 and 
onStop()
 in
all situations except one: when you call 
finish()
 from
within the 
onCreate()
 method.
In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call 
finish()
 from
within
onCreate()
 to
destroy the activity. In this case, the system immediately calls 
onDestroy()
 without
calling any of the other lifecycle methods.

onPause()--

When the system calls 
onPause()
 for
your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity and it will soon enter the Stopped state. You should usually use the 
onPause()
 callback
to:
Stop animations or other ongoing actions that could consume CPU.
Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
Generally, you should not use 
onPause()
 to
store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage within
onPause()
 is
when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during 
onPause()
,
such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during 
onStop()
).
You
should keep the amount of operations done in the 
onPause()
 method
relatively simple in order to allow for a speedy transition to the user's next destination if your activity is actually being stopped.

Once
your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final 
onDestroy()
 callback,
so it's important you use 
onStop()
 to
release resources that might leak memory.

Although
the 
onPause()
 method
is called before 
onStop()
,
you should use 
onStop()
 to
perform larger, more CPU intensive shut-down operations, such as writing information to a database.

@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

    // Release the Camera because we don't need it when paused
    // and other activities might need to use it.
    if (mCamera != null) {
        mCamera.release()
        mCamera = null;
    }
}


onResume--

 you
should implement 
onResume()
 to
initialize components that you release during 
onPause()
 and
perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init
    }
}

onStop()--

Once your activity is stopped, the system might destroy the instance if it needs to recover system memory.
In extreme cases, the system
might simply kill your app process
without calling the activity's final 
onDestroy()
 callback,
so it's important you use 
onStop()
 to release resources that might leak
memory.

Although the 
onPause()
 method
is called before 
onStop()
, you should use 
onStop()
 to
perform larger, more CPU intensive shut-down operations, such as writing information to a database.
When
your activity is stopped, the 
Activity
 object
is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each 
View
 in
the layout, so if the user entered text into an 
EditText
 widget,
that content is retained so you don't need to save and restore it.

When
your activity is destroyed because the user presses Backor
the activity finishes itself, the system's concept of that
Activity
 instance
is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual 
Activity
instance
is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system
uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a 
Bundle
 object.

By
default, the system uses the 
Bundle
 instance
state to save information about each 
View
 object
in your activity layout (such as the text value entered into an 
EditText
 object).
So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables
that track the user's progress in the activity.

Note: In
order for the Android system to restore the state of the views in your activity, each view must have a unique ID,
supplied by the 
android:id
 attribute.

Note: Even
if the system destroys your activity while it's stopped, it still retains the state of the 
View
 objects
(such as text in an 
EditText
)
in a 
Bundle
 (a
blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next
lesson talks more about using a 
Bundle
 to
save other state data in case your activity is destroyed and recreated).

Your
activity will be destroyed and recreated each time the user rotates the screen

 However, because your 
onStop()
 method
should essentially clean up all your activity's resources, you'll need to re-instantiate them when the activity restarts. Yet, you also need to instantiate them when your activity is created for the first time (when there's no existing instance of the activity).
For this reason, you should usually use the 
onStart()
 callback
method as the counterpart to the 
onStop()
 method,
because the system calls 
onStart()
 both
when it creates your activity and when it restarts the activity from the stopped state.

onStart()--

because
the user might have been away from your app for a long time before coming back it, the
onStart()
 method
is a good place to verify that required system features are enabled:

@Override
protected void onStart() {
    super.onStart();  // Always call the superclass method first
   
    // The activity is either being restarted or started for the first time
    // so this is where we should make sure that GPS is enabled
    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
   
    if (!gpsEnabled) {
        // Create a dialog here that requests the user to enable GPS, and use an intent
        // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
        // to take the user to the Settings screen to enable GPS
c8b
when they click "OK"
    }
}

@Override
protected void onRestart() {
    super.onRestart();  // Always call the superclass method first
   
    // Activity being restarted from stopped state    
}


在Activity被系统摧毁时系统保存Activity信息,在Activity被重新创建时取出之前保存的信息--

To save additional data about the activity state, you must override the 
onSaveInstanceState()
 callback
method. The system calls this method when the user is leaving your activity and passes it the 
Bundle
 object
that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same 
Bundle
 object
to both the 
onRestoreInstanceState()
 and 
onCreate()
 methods.



Figure 2. As the system begins to stop your activity, it calls 
onSaveInstanceState()
 (1)
so you can specify additional state data you'd like to save in case the 
Activity
 instance
must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the 
onCreate()
 method
(2) and the
onRestoreInstanceState()
 method
(3).

Save Your Activity State

As your activity begins to stop, the system calls 
onSaveInstanceState()
 so
your activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of the activity's view hierarchy, such as the text in an 
EditText
 widget
or the scroll position of a
ListView
.

To save additional state information for your activity, you must implement 
onSaveInstanceState()
 and
add key-value pairs to the 
Bundle
 object.
For example:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
   
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}


Caution: Always call the superclass implementation of 
onSaveInstanceState()
 so
the default implementation can save the state of the view hierarchy.


Restore Your Activity State

When your activity is recreated after it was previously destroyed, you can recover your saved state from the
Bundle
 that
the system passes your activity. Both the 
onCreate()
 and 
onRestoreInstanceState()
 callback
methods receive the same 
Bundle
 that contains
the instance state information.

Because the 
onCreate()
 method
is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state 
Bundle
 is
null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

For example, here's how you can restore some state data in 
onCreate()
:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
   
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}


Instead of restoring the state during 
onCreate()
 you
may choose to implement 
onRestoreInstanceState()
,
which the system calls after the 
onStart()
 method.
The system calls 
onRestoreInstanceState()
 only
if there is a saved state to restore, so you do not need to check whether the 
Bundle
 is
null:
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
   
    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}


Caution: Always call the superclass implementation of 
onRestoreInstanceState()
 so
the default implementation can restore the state of the view hierarchy.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: