Activity 关闭显示器时生命周期不匹配

Activity Lifecycle mismatch when turning off the display

为了解决关于 App pause/resume 的一些问题,我通过以下简单的 App 测试了 Activity Lifecycle

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        Log.w("xxx", "create");
    }

    @Override
    public void onStart(){
        super.onStart();
        Log.w("xxx","start");
    }

    @Override
    public void onResume(){
        super.onResume();
        Log.w("xxx","Resume");
    }

    @Override
    public void onPause(){
        super.onPause();
        Log.w("xxx","pause");
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.w("xxx","destroy");
    }

    @Override
    public void onStop(){
        super.onStop();
        Log.w("xxx","stop");
    }

    @Override
    public void onRestart(){
        super.onRestart();
        Log.w("xxx","restart");
    }
}

具有包含 Textview 的简单布局。

我安装了该应用程序并且运行它:

01-28 11:56:09.032 2517-2517/android.se.behy.test W/xxx: create
01-28 11:56:09.035 2517-2517/android.se.behy.test W/xxx: start
01-28 11:56:09.035 2517-2517/android.se.behy.test W/xxx: Resume

并关闭显示(通过按下 on/off 按钮),令人惊讶地看到以下日志:

01-28 11:56:09.032 2517-2517/android.se.behy.test W/xxx: create
01-28 11:56:09.035 2517-2517/android.se.behy.test W/xxx: start
01-28 11:56:09.035 2517-2517/android.se.behy.test W/xxx: Resume

01-28 11:56:20.750 2517-2517/android.se.behy.test W/xxx: pause
01-28 11:56:20.753 2517-2517/android.se.behy.test W/xxx: stop
01-28 11:56:20.809 2517-2517/android.se.behy.test W/xxx: destroy
01-28 11:56:20.843 2517-2517/android.se.behy.test W/xxx: create
01-28 11:56:20.844 2517-2517/android.se.behy.test W/xxx: start
01-28 11:56:20.844 2517-2517/android.se.behy.test W/xxx: Resume
01-28 11:56:20.857 2517-2517/android.se.behy.test W/xxx: pause

问题

通常我希望在关闭显示器时暂停应用程序,但为什么在它之后停止、销毁、创建、启动、恢复和暂停?

检查你的开发者选项,其中在应用程序部分有选项不保留活动,如果选中它会发生

我认为您在关闭显示器时方向会发生变化。大多数手机仅在纵向模式下显示屏幕锁定。所以在锁定屏幕之前,它会旋转到方向,并且此配置更改也会应用到您的应用程序,因此会重新创建它。

尝试在您的应用处于纵向模式时执行相同的操作,它应该会按预期运行。

为避免在配置更改时重新创建 activity,请查看 android:configChanges