Android面试(6): Activity上有Dialog的时候按Home键时的生命周期

实践才是真理,代码测试如下:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("This is testDialog");
                dialog.setMessage("Content...");
                dialog.setCancelable(false);
                dialog.show();
            }
        });
    }

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

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

    @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: ");
    }
}

按 Home 键后显示结果:
Android面试(6): Activity上有Dialog的时候按Home键时的生命周期_第1张图片

总结: 有 Dialog 和 无 Dialog 按 Home 键效果一样:
1. 正常启动:     onCreate() -> onStart() -> onResume()
2. 按 home 键: onPause() -> onStop()
3. 再次启动:      onRestart() -> onStart() -> onResume()

你可能感兴趣的:(Android面试相关,Android面试)