Activity是Android应用中最常用的。Activity有其固有的状态和生命周期。但是Android系统对Activity状态切换的处理往往并不是我们所期望的那样,所以了解并掌握Activity的生命周期,对于开发高质量的Android应用是十分必要的。
Android系统会将当前存在的Activity组织成一个栈。当显示新的Activity时,将其创建后放入栈顶。如果用户按了返回键,顶层的Activity就会被移走,下面的一个Activity就显示出来了。
一个Activity一共有四种状态:
Active: 激活状态。Activity处于栈顶,其可见并拥有焦点。当其他Activity被激活时,此Activity便会进入暂停状态。
Paused:暂停状态。Activity可见,但没有焦点。通常是它前面还有一个透明的或者不是全屏的Activity。
Stopped:停止状态。Activity完全不可见时,便处于此状态。
Inactive: 未激活状态。Activity被关闭后的状态,它也会被从Activity栈中移除。
对Activity在各种状态之间的切换,Android系统提供了完整的事件处理函数。
public class MyActivity extends Activity
{
private String LOG_TAG = "MyApplication";
@Override
public void onCreate(Bundle savedInstanceState)
{
// Initialize activity.
super.onCreate(savedInstanceState);
}
// Called after onCreate has finished, use to restore UI state
@Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
super.onRestoreInstanceState(savedInstanceState);
}
// Called before subsequent visible lifetimes
// for an activity process.
@Override
public void onRestart()
{
// Load changes knowing that the activity has already
// been visible within this process.
super.onRestart();
}
// Called at the start of the visible lifetime.
@Override
public void onStart()
{
// Apply any required UI change now that the Activity is visible.
super.onStart();
}
// Called at the start of the active lifetime.
@Override
public void onResume()
{
// Resume any paused UI updates, threads, or processes required
// by the activity but suspended when it was inactive.
super.onResume();
}
// Called to save UI state changes at the
// end of the active lifecycle.
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
super.onSaveInstanceState(savedInstanceState);
}
// Called at the end of the active lifetime.
@Override
public void onPause()
{
// Suspend UI updates, threads, or CPU intensive processes
// that don’t need to be updated when the Activity isn’t
// the active foreground activity.
super.onPause();
}
// Called at the end of the visible lifetime.
@Override
public void onStop()
{
// Suspend remaining UI updates, threads, or processing
// that aren’t required when the Activity isn’t visible.
// Persist all edits or state changes
// as after this call the process is likely to be killed.
super.onStop();
}
// Called at the end of the full lifetime.
@Override
public void onDestroy()
{
// Clean up any resources including ending threads,
// closing database connections etc.
super.onDestroy();
}
}