Giới thiệu
Từ Android 13 (API 33), ứng dụng phải xin quyền POST_NOTIFICATIONS từ người dùng mới được hiển thị thông báo. Bài viết này hướng dẫn cách kiểm tra xem ứng dụng có quyền hiển thị thông báo hay không.
Các bước thực hiện
Bước 1: Tạo dự án mới
Tạo project Android Studio mới.
Bước 2: Layout đơn giản (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 (kiểm tra quyền)" />
</RelativeLayout>
Bước 3: MainActivity với kiểm tra quyền (src/MainActivity.java)
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
private static final int REQUEST_POST_NOTIFICATIONS = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
// KIỂM TRA QUYỀN TRÊN ANDROID 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
// Chưa có quyền → xin quyền
requestPermissions(
new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
REQUEST_POST_NOTIFICATIONS
);
return;
}
}
// Đã có quyền hoặc Android < 13 → tạo thông báo bình thường
showNotification();
}
private void showNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Thông báo test 😀");
mBuilder.setContentText("Quyền thông báo đã được cấp!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_POST_NOTIFICATIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Đã cấp quyền thông báo", Toast.LENGTH_SHORT).show();
showNotification();
} else {
Toast.makeText(this, "Cần quyền thông báo để hiển thị", Toast.LENGTH_SHORT).show();
}
}
}
}
Bước 4: AndroidManifest.xml (Thêm quyền cho Android 13+)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<!-- Quyền rung (tùy chọn) -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- QUYỀN BẮT BUỘC TỪ ANDROID 13 (API 33) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<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>
Kiểm tra quyền programmatically (API 33+)
// Kiểm tra nhanh
boolean hasPermission = (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) ||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
== PackageManager.PERMISSION_GRANTED;
// Hoặc dùng NotificationManagerCompat (khuyên dùng)
boolean areNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled();
Lưu ý quan trọng
- Android 12L (API 32) và dưới: Không cần xin quyền, tự động có quyền nếu user không tắt trong cài đặt
- Android 13+ (API 33+): Bắt buộc xin runtime permission
POST_NOTIFICATIONS - Nếu user từ chối 2 lần → "Don't ask again", phải hướng dẫn vào Settings bật thủ công
- Dùng
NotificationManagerCompat.areNotificationsEnabled()để kiểm tra trạng thái tổng thể (kể cả user tắt trong Settings)
Chạy thử nghiệm
Cài đặt trên Android 13+ emulator/thiết bị thật. Lần đầu nhấn nút sẽ hiện dialog xin quyền. Chọn "Allow" thì thông báo sẽ hiện. Chọn "Don't allow" thì Toast báo cần quyền.