Android

Activity生命周期中三个不常用的方法:onContentC

2019-06-04  本文已影响16人  12313凯皇

说到Activity的生命周期,我的第一反应就是onCreate()onStart()onResume()onPause()onStop()onDestory()onRestart()这 7 个生命周期方法。不过今天看前辈代码的时候碰到他重写了onPostCreate方法,特此做个笔记。

首先,用一个Demo先将他们执行顺序打印出来:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate: ");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        Log.d(TAG, "onPostCreate: ");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d(TAG, "onPostResume: ");
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        Log.d(TAG, "onContentChanged: ");
    }

}

打印结果:


可以看到,其顺序是这样的:
onContentChanged –> onCreate –> onStart –> onPostCreate –> onResume–> onPostResume –> onPause –> onStop –> onDestroy

下面来分别解释这三个方法的含义:

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
 
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

关于Activity常见的 7 个生命周期可查看我的另外一篇文章:Android四大组件之Activity,其次Activity在异常情况下还会涉及到onSaveInstanceState()onRestoreInstanceState()两个方法,在该文也有讲到。

参考文章Activity生命周期中三个不常用的方法:onContentChanged,onPostCreate,onPostResume

上一篇下一篇

猜你喜欢

热点阅读