ภาพรวม
บทความนี้สาธิตวิธีดึงสถานะ Lifecycle ปัจจุบันของ Activity โดยใช้ getLifecycle().getCurrentState() (ต้องใช้ Lifecycle Library)
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: เพิ่ม Dependency (build.gradle)
dependencies {
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.7.0"
implementation "androidx.lifecycle:lifecycle-common:2.7.0"
}
ขั้นตอนที่ 3: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center" />
</LinearLayout>
ขั้นตอนที่ 4: โค้ดหลัก (java/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
updateLifecycleState();
}
@Override
protected void onStart() {
super.onStart();
updateLifecycleState();
}
@Override
protected void onResume() {
super.onResume();
updateLifecycleState();
}
@Override
protected void onPause() {
super.onPause();
updateLifecycleState();
}
@Override
protected void onStop() {
super.onStop();
updateLifecycleState();
}
@Override
protected void onDestroy() {
super.onDestroy();
updateLifecycleState();
}
private void updateLifecycleState() {
Lifecycle.State currentState = getLifecycle().getCurrentState();
textView.setText("Current Lifecycle State: " + currentState.name());
}
}
Lifecycle States
| State | คำอธิบาย |
|---|---|
| INITIALIZED | สร้าง Activity แล้วแต่ยังไม่ onCreate |
| CREATED | หลัง onCreate() ก่อน onStart() |
| STARTED | หลัง onStart() ก่อน onResume() - มองเห็นได้แต่โฟกัสยังไม่ได้ |
| RESUMED | หลัง onResume() - กำลังทำงานและโฟกัสอยู่ |
| DESTROYED | หลัง onDestroy() |