Android通知声音无法正常工作,需手动在应用信息中授权
Hey there, let's break down why your notification sound only works after manually enabling the permission in app info, and fix it step by step:
Key Issues Identified in Your Code & Permissions
1. Missing POST_NOTIFICATIONS Permission (Android 13+)
Starting from Android 13 (API level 33), apps need to explicitly request the POST_NOTIFICATIONS permission to send notifications (including playing notification sounds). Your manifest doesn't include this permission, which is why you have to manually enable it later.
2. Typo in Notification Channel Creation
In your createNotificationChannel() method, you define channel2 but try to create channel at the end:
manager.createNotificationChannel(channel); // Should be channel2!
This means your custom notification channel isn't actually being created, so your custom sound settings aren't applied.
3. Potential Redundancy in Sound Settings
You're setting the sound both in the notification channel and directly in the NotificationCompat.Builder. While this isn't a critical error, it's better to manage sound settings only via the notification channel (since channels take priority on Android O and above).
Step-by-Step Fixes
1. Add Missing Permission to Manifest
Add the POST_NOTIFICATIONS permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
2. Fix the Notification Channel Typo
Update your createNotificationChannel() method to use the correct channel variable:
private void createNotificationChannel() { Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.tune); AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel2 = new NotificationChannel(CHANNEL_ID_FOR_DELETE_OR_NOT, utilityClass.NOTIFICATION_CHANNEL_NAME_SECOND, NotificationManager.IMPORTANCE_HIGH); channel2.enableVibration(true); channel2.setVibrationPattern(new long[]{300, 300, 300}); channel2.enableLights(true); channel2.setShowBadge(true); channel2.canBypassDnd(); channel2.setSound(sound, attributes); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel2); // Fixed here! } }
3. Request Notification Permission at Runtime (Android 13+)
Before sending notifications, check if you have the POST_NOTIFICATIONS permission, and request it if needed:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityResultLauncher<String> requestNotificationPermission = registerForActivityResult( new ActivityResultContracts.RequestPermission(), isGranted -> { if (isGranted) { // Permission granted, you can send notifications now } else { // Permission denied, handle accordingly (e.g., show a message) } } ); requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS); } }
4. Simplify Notification Builder
Since you've already set the sound in the notification channel, you can remove the setSound() call from the NotificationCompat.Builder to avoid redundancy:
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_FOR_DELETE_OR_NOT) .setSmallIcon(R.drawable.ic_baseline_bookmark_border_24) .setContentTitle("title") .setWhen(System.currentTimeMillis()) .setStyle(new NotificationCompat.BigTextStyle().bigText("")) .setDefaults(DEFAULT_VIBRATE) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .setPriority(NotificationCompat.PRIORITY_MAX) .addAction(R.drawable.ic_baseline_bookmark_border_24, "Mark?", pendingIntent) .build();
Additional Checks
- Make sure your
R.raw.tunefile exists and is a valid audio format (like MP3 or WAV). - Verify that the notification channel ID
CHANNEL_ID_FOR_DELETE_OR_NOTis consistent between the channel creation and notification builder.
Following these steps should resolve the issue, and your notification sound will work without requiring manual permission enabling.
内容的提问来源于stack exchange,提问作者user14604981

