Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเรียกเมธอดหลังหน่วงเวลา (Delay) ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการใช้ Handler และ postDelayed() เพื่อเรียกเมธอดหลังจากหน่วงเวลาที่กำหนด (5 วินาที)

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project

ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16sp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Wait for the Toast to display."
        android:textColor="@android:color/black"
        android:textSize="20sp"/>

</RelativeLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showDelayedToast();
            }
        }, 5000); // 5000 ms = 5 วินาที
    }

    private void showDelayedToast() {
        Toast.makeText(this, "This method is called after a delay!", Toast.LENGTH_SHORT).show();
    }
}

ขั้นตอนที่ 4: Manifest

<?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>

การทดสอบ

รันแอป รอ 5 วินาที - จะแสดง Toast "This method is called after a delay!"

วิธีอื่นๆ ที่ทันสมัยกว่า

1. Kotlin Coroutines (แนะนำสำหรับโปรเจกต์ Kotlin)

lifecycleScope.launch {
    delay(5000)
    showDelayedToast()
}

2. Java 8 Lambda (API 24+)

new Handler(Looper.getMainLooper()).postDelayed(() -> showDelayedToast(), 5000);

3. Runnable แบบแยกตัวแปร (ป้องกัน Memory Leak)

private final Handler handler = new Handler(Looper.getMainLooper());
private final Runnable delayedRunnable = this::showDelayedToast;

// เริ่ม
handler.postDelayed(delayedRunnable, 5000);

// ยกเลิก (ใน onDestroy)
handler.removeCallbacks(delayedRunnable);

ข้อควรระวัง

  • Memory Leak: หาก Activity ถูก Destroy ก่อน Delay เสร็จ ให้ยกเลิกด้วย removeCallbacks() ใน onDestroy()
  • ใช้ Handler(Looper.getMainLooper()) แทน Constructor ไม่มีอาร์กิวเมนต์ (Deprecated API 30+)
  • สำหรับงาน Background ที่ซับซ้อน ให้ใช้ WorkManager หรือ Coroutines