Android/Java ดู Activity Lifecycle

ดูเมธอดต่างๆของ Android Activity Lifecycle ด้วยการ log ออกมาดู

MethodDescription
onCreatecalled when activity is first created.
onStartcalled when activity is becoming visible to the user.
onResumecalled when activity will start interacting with the user.
onPausecalled when activity is not visible to the user.
onStopcalled when activity is no longer visible to the user.
onRestartcalled after your activity is stopped, prior to start.
onDestroy called before the activity is destroyed.  

ไฟล์ที่เกี่ยวข้อง

  • MainActivity.java

MainActivity.java

package com.phaisarn.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    String tag = "mylog";

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

        Log.v(tag, "[onCreate]");
    }

    // invoked when the activity may be temporarily destroyed, save the instance state here
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // outState.putString(GAME_STATE_KEY, mGameState);
        // outState.putString(TEXT_VIEW_KEY, mTextView.getText());

        // call superclass to save any view hierarchy
        super.onSaveInstanceState(outState);
        Log.v(tag, "[onSaveInstanceState]");
    }

    // This callback is called only when there is a saved instance that is previously saved by using
    // onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
    // other state here, possibly usable after onStart() has completed.
    // The savedInstanceState Bundle is same as the one used in onCreate().
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.v(tag, "[onRestoreInstanceState]");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.v(tag, "[onStart]");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.v(tag, "[onResume]");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.v(tag, "[onPause]");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.v(tag, "[onStop]");
    }

    @Override
    public void onRestart() {
        super.onRestart();
        Log.v(tag, "[onRestart]");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(tag, "[onDestroy]");
    }
}

การดู log ให้เปิด logcat ออกมาดู View > Tool Windows > Logcat

เลือกเครื่อง เลือก application เลือกระดับของ log เป็น Verbose แล้วพิมพ์ mylog เพื่อ filter log ให้เหลือน้อยลงจะได้ดูง่ายขึ้น

Link