ภาพรวม
ตัวอย่างนี้สาธิตวิธีสร้างการแจ้งเตือนที่ทำงานได้แม้แอปจะถูกปิดหรืออยู่ในพื้นหลัง โดยใช้ Foreground Service ร่วมกับ Timer และ Handler เพื่อสร้างการแจ้งเตือนเป็นระยะ
ขั้นตอนที่ 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="16dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="closeApp"
android:text="Close App for Notification" />
</RelativeLayout>
ขั้นตอนที่ 3: MainActivity.java
package app.tutorialspoint.com.notifyme;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStop() {
super.onStop();
// เริ่ม Service เมื่อแอปหยุดทำงาน (ปิดหรือไปพื้นหลัง)
startService(new Intent(this, NotificationService.class));
}
public void closeApp(View view) {
finish(); // ปิด Activity
}
}
ขั้นตอนที่ 4: NotificationService.java (Foreground Service)
package app.tutorialspoint.com.notifyme;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
private Timer timer;
private TimerTask timerTask;
private final String TAG = "NotificationService";
private int intervalSeconds = 5;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
startTimer();
// START_STICKY: ระบบจะรีสตาร์ท Service หากถูกฆ่า
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
// สร้าง Notification Channel สำหรับ Foreground Service
createNotificationChannel();
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
stopTimerTask();
super.onDestroy();
}
private void createNotificationChannel() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "Background Notifications",
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
// ใช้ Handler เพื่อรันบน Main Thread
final Handler handler = new Handler();
public void startTimer() {
timer = new Timer();
initializeTimerTask();
// เริ่มหลัง 5 วินาที แล้วทุก 5 วินาที
timer.schedule(timerTask, 5000, intervalSeconds * 1000);
}
public void stopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
@Override
public void run() {
handler.post(() -> createNotification());
}
};
}
private void createNotification() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(), default_notification_channel_id)
.setContentTitle("Background Notification")
.setContentText("App is closed but still notifying!")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
}
assert manager != null;
manager.notify((int) System.currentTimeMillis(), builder.build());
}
}
ขั้นตอนที่ 5: AndroidManifest.xml - ประกาศ Service และ Permission
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<!-- สำหรับ Foreground Service (Android 9+) -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.VIBRATE" />
<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>
<!-- ประกาศ Service -->
<service
android:name=".NotificationService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="dataSync">
<intent-filter>
<action android:name="app.tutorialspoint.com.notifyme.NotificationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>
คำอธิบายสำคัญ
- Foreground Service: ทำงานต่อเนื่องแม้แอปปิด ต้องแสดง Notification อยู่ตลอด (Android 8+)
- START_STICKY: ระบบจะรีสตาร์ท Service อัตโนมัติหากถูกฆ่าเพื่อหน่วยความจำ
- Timer + Handler: Timer รันบน Background Thread, Handler สลับมาทำงานบน Main Thread เพื่อสร้าง Notification
- Permission: ต้องขอ FOREGROUND_SERVICE (API 28+) และ POST_NOTIFICATIONS (API 33+)
หมายเหตุสำหรับ Android 12+ (API 31+)
ต้องขอ Permission POST_NOTIFICATIONS จากผู้ใช้ใน Runtime และประกาศ foregroundServiceType ที่เหมาะสม