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

วิธีรัน Android Service ในพื้นหลังตลอดเวลาด้วย Kotlin

ตัวอย่างนี้สาธิตวิธีสร้าง Foreground/Background Service ที่ทำงานต่อเนื่อง แม้แอปจะถูกปิดหรือถูกลบออกจาก Recent Apps โดยใช้ START_STICKY และการรีสตาร์ท Service ใน onTaskRemoved()

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

Android Studio → New Project → Empty Activity

ขั้นตอนที่ 2: 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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Background Service Demo"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Start Background Service"
        android:textSize="16sp"
        android:textStyle="bold" />

</RelativeLayout>

ขั้นตอนที่ 3: สร้าง Service Class (MyService.kt)

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.widget.Toast

class MyService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Toast.makeText(applicationContext, "Service started in background", Toast.LENGTH_SHORT).show()
        // สำคัญ: คืนค่า START_STICKY เพื่อให้ระบบรีสตาร์ท Service หากถูก Kill
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        // เมื่อผู้ใช้สวายปิดแอปจาก Recent Apps ให้รีสตาร์ท Service ใหม่
        val restartIntent = Intent(applicationContext, this.javaClass)
        restartIntent.setPackage(packageName)
        startService(restartIntent)
        super.onTaskRemoved(rootIntent!!)
    }
}

ขั้นตอนที่ 4: เริ่ม Service จาก MainActivity

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "Service Demo"

        val btnStart = findViewById

ขั้นตอนที่ 5: ลงทะเบียน Service ใน AndroidManifest.xml

<manifest ...>
    <application ...>
        <activity android:name=".MainActivity" ... />

        <!-- สำคัญ: exported="true" สำหรับ Android 12+ -->
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />
    </application>
</manifest>

⚠️ ข้อควรระวังสำคัญ (Android 8.0+ / API 26+)

  • Service แบบนี้ถือว่าเป็น Background Service ซึ่ง Android 8+ จำกัดการทำงาน
  • สำหรับ Production ควรใช้ Foreground Service พร้อม Notification แทน
  • ต้องขอ Permission FOREGROUND_SERVICE และสร้าง Notification Channel
  • โค้ดตัวอย่างนี้เหมาะสำหรับการเรียนรู้พื้นฐานเท่านั้น

ทดสอบ

  1. รันแอป → กดปุ่ม Start Service
  2. กด Home → สวายปิดแอปจาก Recent Apps
  3. Service จะทำงานต่อและแสดง Toast ทุกครั้งที่ถูก Restart