
Android 13(API 33)起,应用需动态申请 POST_NOTIFICATIONS 权限才能显示通知;若未授权,即使通知渠道创建成功、构建逻辑无误,通知也不会显示。
android 13(api 33)起,应用需动态申请 `post_notifications` 权限才能显示通知;若未授权,即使通知渠道创建成功、构建逻辑无误,通知也不会显示。
在 Android 13 及更高版本中,系统强制要求应用在首次显示通知前,显式请求并获得用户授予 android.permission.POST_NOTIFICATIONS 权限。这是导致您代码在 onCreate() 中调用 nm.notify() 后通知“静默失败”的根本原因——系统直接丢弃了未授权的通知请求,且不抛出异常或日志警告(仅在 Logcat 中可能看到 NotificationService: Permission denied 类似提示)。
✅ 正确实现步骤
-
在 AndroidManifest.xml 中声明权限(必需,但仅声明不够):
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
-
在 onCreate() 中检查并请求权限(关键修复):
private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 1001;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// ✅ 第一步:检查是否已授权
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
// ✅ 第二步:请求权限(Android 13+ 专属)
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.POST_NOTIFICATIONS},
NOTIFICATION_PERMISSION_REQUEST_CODE);
return; // 等待用户授权后再触发通知
}
}
// ✅ 第三步:仅在权限就绪后构建并发送通知
showNotification();}
3. **处理权限回调结果**(必须重写):
```java
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == NOTIFICATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// ✅ 用户同意 → 立即显示通知
showNotification();
} else {
// ⚠️ 用户拒绝 → 建议引导至设置页或提示必要性
Toast.makeText(this, "通知权限被拒绝,无法显示消息", Toast.LENGTH_LONG).show();
}
}
}-
将通知逻辑封装为独立方法(提升可维护性):
private void showNotification() { NotificationManager nm = getSystemService(NotificationManager.class); // 创建通知渠道(Android 8.0+ 必须) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "默认通知通道"; String description = "用于接收应用常规消息"; NotificationChannel channel = new NotificationChannel( CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(description); nm.createNotificationChannel(channel); } // 构建通知(兼容低版本) NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.small_icon) .setContentTitle("新消息") .setContentText("New Message") .setSubText("subText") .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH); nm.notify(1245, builder.build()); }
⚠️ 注意事项
- POST_NOTIFICATIONS 权限仅适用于 Android 13(API 33)及以上,低版本无需请求(但仍需在 Manifest 中声明以避免编译错误)。
- 不要跳过权限检查直接调用 notify()——即使 Build.VERSION.SDK_INT
- 测试时请使用真机或 Android 13+ 模拟器,并在「设置 → 应用 → 权限管理」中确认通知权限状态。
- 若用户永久拒绝权限,shouldShowRequestPermissionRationale() 可用于判断是否需二次解释,增强用户体验。
通过以上改造,您的通知将在 onCreate() 中稳定触发,同时符合 Android 最新权限规范。


















