Giới thiệu
Để nhận thông báo khi app bị kill (swipe khỏi recent apps), cần dùng **Foreground Service** kết hợp với **Firebase Cloud Messaging (FCM)** hoặc **WorkManager/AlarmManager** cho local notification. Bài này demo cách dùng Service chạy nền tạo thông báo định kỳ.
Kiến trúc
- MainActivity: UI chính, nút "Đóng app để test".
- NotificationService (extends Service): Chạy nền, dùng Timer/Handler tạo thông báo mỗi 5 giây.
- START_STICKY: System restart service nếu bị kill do bộ nhớ thấp.
Code hoàn chỉnh
1. 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="Đóng app để test thông báo nền" />
</RelativeLayout>
2. MainActivity.java
package com.example.backgroundnotification;
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();
// Khởi động service khi app không còn foreground
startService(new Intent(this, NotificationService.class));
}
public void closeApp(View view) {
finishAffinity(); // Đóng hoàn toàn app
}
}
3. NotificationService.java
package com.example.backgroundnotification;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service {
private static final String CHANNEL_ID = "bg_notif_channel";
private static final String CHANNEL_NAME = "Background Notifications";
private Timer timer;
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();
return START_STICKY; // Restart nếu bị kill
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
private void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
handler.post(this::showNotification);
}
}, 5000, 5000); // Delay 5s, repeat 5s
}
private void showNotification() {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("App đang chạy nền")
.setContentText("Thông báo từ Service - " + System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify((int) System.currentTimeMillis(), notification);
}
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
4. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.backgroundnotification">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Android 13+ -->
<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/Theme.BackgroundNotification">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotificationService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
Lưu ý quan trọng (Android 8.0+)
- Foreground Service bắt buộc: Service chạy nền lâu dài phải gọi
startForeground()với notification ongoing. Code trên chỉ demo đơn giản, thực tế cần upgrade thành Foreground Service. - Doze Mode / App Standby: Timer có thể bị delay. Dùng
WorkManagerhoặcAlarmManager.setExactAndAllowWhileIdle()cho timing chính xác. - FCM (Firebase Cloud Messaging): Cách chuẩn cho push notification từ server khi app đóng. Data message vẫn xử lý được khi app kill.
- Android 13+ (API 33): Cần quyền
POST_NOTIFICATIONSruntime permission.
Cải tiến cho Production
// Trong onStartCommand - bắt buộc cho Foreground Service
Notification ongoingNotif = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Đang chạy nền")
.setContentText("Nhận thông báo...")
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.build();
startForeground(1, ongoingNotif); // ID = 1