新的activity启动后,前一个activity就会停止,系统将其保存到一个历史栈中。返回时,顶层的activity就会被销毁,之前的activity就会重新显示在屏幕上。当然,如果系统内存不足,后台的activity就会被销毁。
androidmanifest中的intent-filter标签指定了初始启动的activity
Activity生命周期:由android系统管理
onCreate()
onStart()
onRestart()
onResume()
onPause()
onStop()
onDestroy()
package com.example.ex; import android.os.Bundle; import android.util.Log; import android.app.Activity; public class MainActivity extends Activity { private static final String LIFETAG="Aclifecycle"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart(){ super.onStart(); Log.d(LIFETAG,"onstart method is executed"); } @Override protected void onResume(){ super.onResume(); Log.d(LIFETAG,"onresume method is executed"); } @Override protected void onRestart(){ super.onRestart(); Log.d(LIFETAG,"onrestart method is executed"); } @Override protected void onPause(){ super.onPause(); Log.d(LIFETAG,"onpause method is executed"); } @Override protected void onStop(){ super.onStop(); Log.d(LIFETAG,"onstop method is executed"); } @Override protected void onDestroy(){ super.onDestroy(); Log.d(LIFETAG,"ondestroy method is executed"); } }
启动程序:
执行3个生命周期方法:
onCreate() activity第一次创建时调用
onStart() activity对用户即将可见时调用
onResume() activity即将与用户交互时调用 磁石activity进入栈顶
在这之后总是调用onpause()方法
按下模拟器的拨号按钮,activity失去焦点,观察logcat中信息:
onPause()在activity启动另一个activity时调用。下一个activity必须等待这个方法返回后再启动。
onStop()在一个新的activity启动,其他activity被切换到前台,当前activity被销毁时都会调用。
点击返回键:
当activity从stopped状态启动时调用OnRestart()方法,后面总是调用onstart()方法。
再次按返回键,关闭activity:
很多时候,在关闭一个activity后,用户期望再次返回到哪个activity,它仍保持离开时的样子,这时候就需要考虑如何保存activity。
为了获取activity被杀死前的状态,应该为activity实现onSaveInstanceState()方法。它在activity被系统销毁前调用。
用户造成的销毁(如按下返回键),不会调用。
最好用onpause()方法来保存在停止与用户交互前更改过的数据。
总结:
oncreat() ondestroy()创建和销毁
onstart() onstop() 可见和不可见
onresume() onpause()焦点和无焦点
onrestart() 在onstop()以后却没有执行ondestroy()方法时调用。如调用了ondestroy则调用onCreat。