1. 程式人生 > >Android--測試Activity的生命週期事件及其回撥方法

Android--測試Activity的生命週期事件及其回撥方法

//activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/btn_finish"

        android:text="結束程式"/>

</android.support.constraint.ConstraintLayout>
  
//MainAcyivity

package com.example.abaka;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static String TAG="LIFTCYCLE";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Log.i(TAG,"(1)onCreate()");

        Button button=(Button)findViewById(R.id.btn_finish);

        button.setOnClickListener(new View.OnClickListener(){

            public void onClick(View view) {

                finish();

            }

            });

    }

    @Override

    public void onStart(){

        super.onStart();

        Log.i(TAG,"(2)onStart");

    }

    @Override

    public void onRestoreInstanceState(Bundle savedInstanceState){

        super.onRestoreInstanceState(savedInstanceState);

        Log.i(TAG,"(3)onRestoreInstanceState()");

    }

    @Override

    public void onResume(){

        super.onResume();

        Log.i(TAG,"(4)onResume()");

    }

    @Override

    public void  onSaveInstanceState(Bundle savedInstanceState){

        super.onSaveInstanceState(savedInstanceState);

        Log.i(TAG,"(5)onSaveInstanceState()");

    }

    @Override

    public void onRestart(){

        super.onRestart();

        Log.i(TAG,"(6)onRestart");

    }

    @Override

    public void onPause(){

        super.onPause();

        Log.i(TAG,"(7)onPause()");

    }

    @Override

    public void onStop(){

        super.onStop();

        Log.i(TAG,"(8)onStup");

    }

    @Override

    public void onDestroy(){

        super.onDestroy();

        Log.i(TAG,"(9)onDestroy()");

    }

}

在這裡插入圖片描述

完全生命週期的LogCat輸出:

在這裡插入圖片描述