ภาพรวม
ตัวอย่างนี้สาธิตวิธีการรันเมธอด (Method) ทุกๆ 10 วินาทีใน Android โดยใช้ Handler และ Runnable ด้วย Kotlin
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Running a method every Ten seconds"
android:textColor="@android:color/holo_orange_dark"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val handler = Handler()
private var runnable: Runnable? = null
private val delay = 10000L // 10 วินาที
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
override fun onResume() {
super.onResume()
runnable = Runnable {
// งานที่ต้องการรันทุก 10 วินาที
Toast.makeText(this@MainActivity, "This method will run every 10 seconds", Toast.LENGTH_SHORT).show()
// จัดตารางรันครั้งถัดไป
handler.postDelayed(runnable!!, delay)
}
// เริ่มรันครั้งแรก
handler.postDelayed(runnable!!, delay)
}
override fun onPause() {
super.onPause()
// ยกเลิกการรันเมื่อ Activity ไม่อยู่หน้าจอ (ป้องกัน Memory Leak)
runnable?.let { handler.removeCallbacks(it) }
}
}
ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml
ใช้การตั้งค่ามาตรฐาน
ทดสอบการทำงาน
รันแอป จะเห็น Toast แสดงข้อความทุกๆ 10 วินาที
แนวทางปฏิบัติที่ดีกว่า (Best Practices)
- Coroutines + Flow: ใช้
kotlinx.coroutinesและflow { while(true) { delay(10000); emit(...) } }สำหรับโค้ดที่ทันสมัยและปลอดภัยกว่า - WorkManager: สำหรับงานที่ต้องรันในพื้นหลังแม้แอปจะปิด (PeriodicWorkRequest)
- AlarmManager: สำหรับการตั้งเวลาที่แม่นยำแม้อุปกรณ์จะอยู่ในโหมด Doze
- หลีกเลี่ยง Handler ใน Activity: อาจทำให้ Memory Leak หากไม่ล้างใน onPause/onDestroy