Ví dụ này minh họa cách gửi thông báo từ Service trong Android sử dụng Kotlin.
Bước 1: Tạo dự án mới
Trong Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.
Bước 2: Cấu hình layout chính (activity_main.xml)
Thêm mã sau vào 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>
Bước 3: Viết mã MainActivity.kt
Thêm mã sau vào 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)
}
}
Bước 4: Tạo Service (ExampleService.kt)
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)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
return START_NOT_STICKY
}
override fun onBind(p0: Intent?): IBinder? = null
}
Bước 5: Cấu hình AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<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>
</intent-filter>
</activity>
<service android:name=".ExampleService" />
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị Android thực với máy tính. Từ Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động và kiểm tra màn hình hiển thị.
Lưu ý quan trọng: Từ Android 8.0 (API 26), Service chạy nền bị hạn chế. Phải dùng Foreground Service kèm Notification (như ví dụ). Từ Android 12 (API 31), cần khai báo quyền
FOREGROUND_SERVICEvà loại service cụ thể trong manifest (ví dụ:android:foregroundServiceType="dataSync").