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

วิธีส่ง Notification จาก Service ใน Android ด้วย Kotlin

บทนำ

ตัวอย่างนี้สาธิตการสร้าง Foreground Service ที่แสดง Notification ค้างอยู่บนแถบสถานะ ใน Android โดยใช้ Kotlin

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

สร้างโปรเจกต์ใหม่ใน Android Studio

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

เพิ่มโค้ดใน res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startService"
        android:text="Start Service" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="stopService"
        android:text="Stop Service" />

</LinearLayout>

ขั้นตอนที่ 3: MainActivity.kt

เพิ่มโค้ดใน src/MainActivity.kt:

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    lateinit var editText: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        editText = findViewById(R.id.editText)
    }

    fun startService(view: View) {
        val input: String = editText.text.toString()
        val serviceIntent = Intent(this, ExampleService::class.java)
        serviceIntent.putExtra("inputExtra", input)
        ContextCompat.startForegroundService(this, serviceIntent)
    }

    fun stopService(view: View) {
        val serviceIntent = Intent(this, ExampleService::class.java)
        stopService(serviceIntent)
    }
}

ขั้นตอนที่ 4: สร้าง Service (ExampleService.kt)

สร้าง Class ใหม่ชื่อ ExampleService ขยายจาก Service:

import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat

class ExampleService : Service() {
    private val channelId = "Notification from Service"

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= 26) {
            val channel = NotificationChannel(
                channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
        }
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val input = intent.getStringExtra("inputExtra")
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)

        val notification: Notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.notification) // ต้องมีไอคอนใน drawable
            .setContentIntent(pendingIntent)
            .build()

        startForeground(1, notification)
        return START_NOT_STICKY
    }

    override fun onBind(p0: Intent?): IBinder? = null
}

ขั้นตอนที่ 5: AndroidManifest.xml

เพิ่ม Permission และประกาศ Service:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

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

การทดสอบ

รันแอป ป้อนข้อความ กด "Start Service" จะปรากฏ Notification ค้างอยู่ กด "Stop Service" จะหายไป

วิธีส่ง Notification จาก Service ใน Android ด้วย Kotlin วิธีส่ง Notification จาก Service ใน Android ด้วย Kotlin

ข้อกำหนด Android 8.0+: Foreground Service ต้องสร้าง Notification Channel และเรียก startForeground() ภายใน 5 วินาที มิฉะะระบบจะ ANR