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

Cách gọi onDestroy() của Activity trong ứng dụng Android?

Giới thiệu

Bài viết minh họa vòng đời Activity và cách onDestroy() được gọi khi Activity bị hủy. Lưu ý: Không nên gọi onDestroy() trực tiếp, hãy dùng finish().

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

Bước 1: Tạo dự án mới

Tạo project Android Studio.

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="32dp"
        android:text="Hủy Activity"
        android:textColor="@color/colorPrimary"
        android:textSize="32dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Bước 3: Ghi log vòng đời (src/MainActivity.java)

package com.sample.q2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    public static final String MY_TAG = "Destroy";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(MY_TAG, "onCreate");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(MY_TAG, "onDestroy");
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Mở Logcat lọc tag "Destroy". Nhấn nút Back hoặc vuốt thoát app để thấy log onDestroy.

Cách gọi onDestroy() của Activity trong ứng dụng Android?

Quan trọng về onDestroy()

  • Không bao giờ gọi onDestroy() trực tiếp - Đây là callback của hệ thống
  • Dùng finish() để yêu cầu kết thúc Activity
  • onDestroy() gọi khi: finish(), system kill do thiếu bộ nhớ, thay đổi cấu hình (rotate) nếu không handle
  • Dùng để: giải phóng tài nguyên (thread, listener, sensor, database, handler)
  • Không đảm bảo luôn được gọi (system kill process đột ngột)

Thứ tự vòng đời điển hình

onCreate → onStart → onResume → (running) → onPause → onStop → onDestroy