思路:1.继承Activity
2.重写方法(onCreate、onStart、onPause、onResume、onStop、onDestroy...)
3.模拟场景(首次启动、屏幕变黑、按Home键、屏幕亮起、退出、进程杀死...),打印日志、分析。
实现:
1)java代码
/** * Created by mb on 2015/1/28. * 测试生命周期 */public class TestActivity extends Activity { private static final String TGA = "TestActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogUtils.v(TGA, "onCreate");//LogUtils是打印日志的工具类 setContentView(R.layout.test_layout); } @Override protected void onStart() { super.onStart(); LogUtils.v(TGA, "onStart"); } @Override protected void onRestart() { super.onRestart(); LogUtils.v(TGA, "onRestart"); } @Override protected void onResume() { super.onResume(); LogUtils.v(TGA, "onResume"); } @Override protected void onPause() { super.onPause(); LogUtils.v(TGA, "onPause"); } @Override protected void onPostResume() { super.onPostResume(); LogUtils.v(TGA, "onPostResume"); } @Override protected void onStop() { super.onStop(); LogUtils.v(TGA, "onStop"); } @Override protected void onDestroy() { super.onDestroy(); LogUtils.v(TGA, "onDestroy"); }}
2)运行程序、查看日志:
<1>首次启动:
01-28 13:27:25.945 3825-3825/com.imeibi.myapp V/TestActivity﹕ onCreate
01-28 13:27:25.960 3825-3825/com.imeibi.myapp V/TestActivity﹕ onStart01-28 13:27:25.960 3825-3825/com.imeibi.myapp V/TestActivity﹕ onResume01-28 13:27:25.960 3825-3825/com.imeibi.myapp V/TestActivity﹕ onPostResume<2>屏幕变黑、按HOME键:
01-28 13:27:40.875 3825-3825/com.imeibi.myapp V/TestActivity﹕ onPause
01-28 13:27:40.914 3825-3825/com.imeibi.myapp V/TestActivity﹕ onStop<3>屏幕亮起、重新启动:
01-28 13:28:17.164 3825-3825/com.imeibi.myapp V/TestActivity﹕ onRestart
01-28 13:28:17.171 3825-3825/com.imeibi.myapp V/TestActivity﹕ onStart01-28 13:28:17.179 3825-3825/com.imeibi.myapp V/TestActivity﹕ onResume01-28 13:28:17.179 3825-3825/com.imeibi.myapp V/TestActivity﹕ onPostResume<4>退出(返回键退出):
01-28 13:28:41.703 3825-3825/com.imeibi.myapp V/TestActivity﹕ onPause
01-28 13:28:42.320 3825-3825/com.imeibi.myapp V/TestActivity﹕ onStop01-28 13:28:42.320 3825-3825/com.imeibi.myapp V/TestActivity﹕ onDestroy<5>进程杀死:
01-28 13:36:26.132 3825-3825/com.imeibi.myapp V/TestActivity﹕ onDestroy
3)分析:
activity有三种基本状态:
(1)Active状态:可见,处于屏幕前景(当前task的栈顶Activity处于Active状态),同一时刻只能有一个Activity处于Active状态;
(2)Paused状态:不可见,失去焦点,但依然是活动状态;
(3)stopped状态:不可见,但依然保持多有状态和内存信息。
通过上面的信息再结合右图(最好自己动手试一试),我相信应该对activity生命周期有所了解了吧。
好了,通过上面的信息,再结合上图应该对activity有一定的了解了。自己再动手试一试,应该差不多了。
若有不足之处,希望大胆指出,刚学android,互相学习......