这几天找工作,被问到这个问题,实际是看过的,也了解,当然面试的时候了解是不可以的(实际工作的时候看一下不就知道了,但是为了获取信任)。写了一个Demo帮助理解。简而言之,onCreate和onDestroy对应,是在创建和销毁Activity时调用的,onStart和onStop对应,是占有全部屏幕即前台和失去全部屏幕即后台时对应调用的,onResume和onPause对应,是在部分屏幕被其他活动占有和占有部分屏幕的活动消失的时候调用的。
package com.example.lifecycle; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class MainActivity extends Activity { String TAG = "LifeCycle_Display"; @Override protected void onCreate(Bundle savedInstanceState) { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); // setContentView(R.layout.activity_main); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onCreate(savedInstanceState); } protected void onStart() { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onStart(); } protected void onResume() { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onResume(); } protected void onPause() { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onPause(); } protected void onStop() { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onStop(); } protected void onDestroy() { Toast.makeText(this, Thread.currentThread().getStackTrace()[2].getMethodName(), Toast.LENGTH_LONG).show(); Log.i(TAG, Thread.currentThread().getStackTrace()[2].getMethodName()); super.onDestroy(); } }
测试验证码