上机3:验证Activity生命周期
修改教材P56的例子3.1,验证P55页Activity生命周期。需要验证尽可能的生命周期路径,特别是onPause() -->onResume()。
1 class MyObserver implements LifecycleObserver { 2 3 private static final String TAG = MyObserver.class.getSimpleName(); 4 5 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 6 public void onCreate() { 7 Log.d(TAG, "onCreate called"); 8 } 9 10 @OnLifecycleEvent(Lifecycle.Event.ON_START) 11 public void onStart() { 12 Log.d(TAG, "onStart called"); 13 } 14 15 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) 16 public void onResume() { 17 Log.d(TAG, "onResume called"); 18 } 19 20 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) 21 public void onPause() { 22 Log.d(TAG, "onPause called"); 23 } 24 25 @OnLifecycleEvent(Lifecycle.Event.ON_STOP) 26 public void onStop() { 27 Log.d(TAG, "onStop called"); 28 } 29 30 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 31 public void onDestroy() { 32 Log.d(TAG, "onDestroy called"); 33 } 34 35 @OnLifecycleEvent(Lifecycle.Event.ON_ANY) 36 public void onAny() { 37 Log.d(TAG, "onCreate | onStart | onResume | onPause | onStop | onDestroy called"); 38 } 39 }
1 public class MyActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 // ... 6 getLifecycle().addObserver(new MyObserver()); 7 } 8 }