简体   繁体   中英

No sound when displaying notification

My app won't play any sound (or vibrate) when I display notification.

Notification code:

Uri sound = Settings.System.DEFAULT_NOTIFICATION_URI;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentTitle(title)
                .setContentText(text)
                .setSound(sound, AudioManager.STREAM_NOTIFICATION)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSmallIcon(R.drawable.small_icon)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setContentIntent(contentIntent);

Notification manager:

NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String channelName = getChannelName(channel);
            Uri sound = Settings.System.DEFAULT_NOTIFICATION_URI;

            AudioAttributes attribute = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();

            NotificationChannel mChannel = new NotificationChannel(channel, channelName, NotificationManager.IMPORTANCE_DEFAULT);
            mChannel.setSound(sound, attribute);

            if (manager != null) {
                manager.createNotificationChannel(mChannel);
            }
        }

I've looked at many older questions, but I didn't find any solution.

I test this on android 9.0.0

You create a Notification.Builder but you never create a Notification ... Use Builder.build() to get one. As well, you get a NotificationManager but you never as kit to display a Notification . To do this, use manager.notify() .

You may have set some other priority for notification channel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM