Giới thiệu
Thông báo cục bộ (local notification) được tạo bởi chính ứng dụng, không cần server. Mặc định tự xóa khi bấm nhờ setAutoCancel(true).
Code mẫu tối giản
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:id="@+id/btnCreateNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tạo thông báo local" />
</RelativeLayout>
MainActivity.java
package com.example.localnotification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "local_channel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Thông báo cục bộ")
.setContentText("Tự xóa khi bấm vào - setAutoCancel(true)")
.setAutoCancel(true); // ==== QUAN TRỌNG ====
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "Local Notifications", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
builder.setChannelId(CHANNEL_ID);
}
manager.notify((int) System.currentTimeMillis(), builder.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.localnotification">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- API 33+ -->
<uses-permission android:name="android.permission.VIBRATE" />
<application ...>
<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>
</application>
</manifest>
Các loại thông báo cục bộ phổ biến
| Loại | Cách tạo | Dùng khi nào |
|---|---|---|
| Instant | NotificationManager.notify() ngay | Thông báo tức thì (chat, email) |
| Scheduled (AlarmManager) | Đặt hẹn giờ qua AlarmManager + BroadcastReceiver | Nhắc lịch, nhắc uống nước |
| Periodic (WorkManager) | WorkManager với PeriodicWorkRequest | Đồng bộ dữ liệu định kỳ |
| Foreground Service | Service.startForeground() | Music player, download, navigation |
Best Practices
- Luôn tạo Notification Channel (API 26+).
- Dùng
setAutoCancel(true)cho thông báo tương tác một lần. - Dùng
setOngoing(true)cho foreground service (không thể vuốt xóa). - Xin quyền
POST_NOTIFICATIONStại runtime (Android 13+). - Gom nhóm thông báo bằng
setGroup()vàsetGroupSummary().