Android Studio按钮触发通知遇权限报错,求解决方案
Android通知权限异常解决办法
问题原因
你的报错是因为Android 13(API 33)及以上版本要求必须申请POST_NOTIFICATIONS权限才能发送通知,你的代码未处理该权限逻辑,因此触发权限异常。
解决步骤
1. 在AndroidManifest.xml中添加权限声明
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
该权限在API33以下版本会自动授予,无需用户确认,直接添加即可兼容全版本。
2. 修正通知渠道的SDK版本判断
通知渠道从Android 8.0(API26)开始强制要求,你当前的Build.VERSION_CODES.O_MR1(API27)范围过窄,改为:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("My Notification", "My Notification", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); }
3. 动态申请权限后发送通知
修改按钮点击逻辑,先检查权限,获得授权后再发送通知:
// 定义权限请求码 private static final int NOTIFICATION_PERMISSION_REQUEST = 1001; // 初始化按钮 Button notificationBtn = findViewById(R.id.NotificationButton); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("My Notification", "My Notification", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } notificationBtn.setOnClickListener(v -> { // 检查是否拥有通知权限 if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { // 申请权限 registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { if (isGranted) { sendNotification(); } else { Toast.makeText(MainActivity.this, "需要开启通知权限才能发送提醒", Toast.LENGTH_SHORT).show(); } }).launch(Manifest.permission.POST_NOTIFICATIONS); } else { // 已有权限,直接发送 sendNotification(); } }); // 抽离通知发送逻辑 private void sendNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "My Notification"); builder.setContentTitle("ALARM Notification") .setContentText("Please Take Your Phone") .setStyle(new NotificationCompat.BigTextStyle()) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSmallIcon(R.drawable.baseline_notifications_24) .setAutoCancel(true); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(MainActivity.this); managerCompat.notify(1, builder.build()); }
额外注意
- 上述代码使用Jetpack推荐的
registerForActivityResult处理权限请求,替代旧版的requestPermissions写法,兼容性更好。 - 若用户拒绝权限,可根据需求引导其前往应用设置页面开启权限,基础场景下用Toast提示即可。
内容的提问来源于stack exchange,提问作者Aldred
相关产品推荐
相关产品推荐

