Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy trạng thái vòng đời hiện tại của Activity trên Android

Giới thiệu

Bài viết hướng dẫn cách lấy trạng thái vòng đời (Lifecycle State) hiện tại của Activity bằng Lifecycle API (AndroidX Lifecycle). Các trạng thái: CREATED, STARTED, RESUMED, DESTROYED, INITIALIZED.

Các bước thực hiện

Bước 1: Thêm dependency (build.gradle)

dependencies {
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.2"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2"
    // Hoặc dùng lifecycle-runtime (Java)
    implementation "androidx.lifecycle:lifecycle-runtime:2.6.2"
}

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvLifecycleState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lifecycle State: "
        android:textSize="20sp" />

    <Button
        android:id="@+id/btnCheckState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Kiểm tra state hiện tại" />

</LinearLayout>

Bước 3: Code (MainActivity.kt)

package com.example.lifecyclestate

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnCheckState.setOnClickListener {
            val currentState = lifecycle.currentState
            tvLifecycleState.text = "Current State: $currentState"
            Toast.makeText(this, "State: $currentState", Toast.LENGTH_SHORT).show()
        }

        // Quan sát thay đổi lifecycle (Optional)
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                logState("ON_CREATE")
            }
            override fun onStart(owner: LifecycleOwner) {
                logState("ON_START")
            }
            override fun onResume(owner: LifecycleOwner) {
                logState("ON_RESUME")
            }
            override fun onPause(owner: LifecycleOwner) {
                logState("ON_PAUSE")
            }
            override fun onStop(owner: LifecycleOwner) {
                logState("ON_STOP")
            }
            override fun onDestroy(owner: LifecycleOwner) {
                logState("ON_DESTROY")
            }
        })
    }

    private fun logState(event: String) {
        val state = lifecycle.currentState
        println("[$event] Current State: $state")
        // Cập nhật UI nếu cần
        runOnUiThread { tvLifecycleState.text = "[$event] State: $state" }
    }
}

Các trạng thái Lifecycle.State

State Mô tả Callback tương ứng
INITIALIZED
Trạng thái khởi tạo, trước onCreate
-
CREATED Sau onCreate, trước onStart onCreate
STARTED Sau onStart, trước onResume (hiển thị nhưng chưa focus) onStart
RESUMED Sau onResume, Activity đang tương tác với user onResume
DESTROYED Sau onDestroy onDestroy

So sánh: getLifecycle() vs ProcessLifecycleOwner

  • lifecycle.currentState: State của Activity/Fragment này.
  • ProcessLifecycleOwner.get().lifecycle.currentState: State của toàn bộ ứng dụng process (foreground/background).

Ứng dụng thực tế

  • Tạm dừng/resume video, music khi Activity không còn RESUMED.
  • Kết nối/ngắt kết nối WebSocket, database, location updates theo lifecycle.
  • Analytics: track screen view khi RESUMED.
  • Đồng bộ dữ liệu khi app về foreground (ProcessLifecycleOwner).

Lưu ý

  • Luôn dùng lifecycle.currentState thay vì tự track biến boolean (isResumed, isStarted...).
  • Dùng DefaultLifecycleObserver (API 24+) thay cho LifecycleObserver + annotation cũ.
  • Fragment có lifecycle riêng biệt, dùng viewLifecycleOwner.lifecycle cho View binding.