Giới thiệu
Ví dụ cơ bản nhất về việc xây dựng thông báo Android sử dụng NotificationCompat.Builder. Phù hợp cho người mới bắt đầu học về hệ thống thông báo Android.
Các bước thực hiện
Bước 1: Tạo dự án mới
Tạo project Android Studio mới với Empty Activity.
Bước 2: Layout nút bấm (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"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:onClick="createNotification"
android:text="Tạo thông báo cơ bản" />
</RelativeLayout>
Bước 3: MainActivity - Xây dựng Notification (src/MainActivity.java)
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this, default_notification_channel_id);
// CẤU HÌNH CƠ BẢN
mBuilder.setContentTitle("Thông báo cho tôi 😀");
mBuilder.setContentText("Điều gì đó quan trọng!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true); // Tự xóa khi nhấn
// NOTIFICATION CHANNEL (BẮT BUỘC TỪ ANDROID O)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "Kênh thông báo chính", importance);
notificationChannel.setDescription("Kênh cho các thông báo quan trọng");
// Tùy chọn: bật rung, đèn, âm thanh
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{0, 500, 200, 500});
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
// ID duy nhất cho mỗi thông báo (dùng timestamp)
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
}
Bước 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<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>
</application>
</manifest>
Giải thích các thành phần chính
NotificationCompat.Builder
Lớp xây dựng thông báo tương thích ngược (backward compatible) từ API 4+.
Các phương thức thiết yếu
setContentTitle()- Tiêu đề chính (bắt buộc)setContentText()- Nội dung chính (bắt buộc)setSmallIcon()- Icon nhỏ trên status bar (bắt buộc)setChannelId()- Kênh thông báo (bắt buộc Android 8+)setAutoCancel(true)- Tự xóa khi user nhấn
Notification Channel (Android 8.0+)
Mỗi kênh có mức độ quan trọng (importance):
IMPORTANCE_HIGH- Hiện heads-up, có âm thanhIMPORTANCE_DEFAULT- Hiện bình thường, có âm thanhIMPORTANCE_LOW- Không heads-up, không âm thanhIMPORTANCE_MIN- Chỉ hiện trong shade, không âm thanhIMPORTANCE_NONE- Không hiển thị nào
Mở rộng nâng cao
Sau khi nắm cơ bản, bạn có thể thêm:
setStyle(new BigTextStyle().bigText(longText))- Văn bản dàisetStyle(new InboxStyle().addLine(...))- Danh sách mụcsetStyle(new BigPictureStyle().bigPicture(bitmap))- Hình ảnh lớnaddAction()- Nút hành độngsetContentIntent(pendingIntent)- Mở app khi nhấnsetLargeIcon(bitmap)- Avatar/hình lớn bên trái
Chạy thử nghiệm
Cài đặt app, nhấn nút "Tạo thông báo cơ bản". Kéo thanh thông báo xuống để xem kết quả.