安卓通知频道声音无法工作

12

我知道这个问题已经有很多帖子了。我尝试过它们所有的方法,以下是我所做的步骤:

首先,我发现一旦一个通道被创建,就无法更改。唯一的方法是重新安装应用程序。所以我尝试了这个方法,但它没有起作用。

其次,有些人说我可以删除这个频道,因此我也使用了这段代码进行了删除操作。

val channelList = mNotificationManager.notificationChannels
        var i = 0
        while (channelList != null && i < channelList.size) {
            Log.d("channelList","channel ID is ${channelList[i].id}")
            //mNotificationManager.deleteNotificationChannel(channelList[i].id)
            i++
        }

然后删除通道后重新创建通道。

第三,我尝试使用新的通知通道,但每次使用新通道时都会出现错误。

这是我正在使用的代码,包括我尝试过的所有解决方案。

 val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build()


        val importance = NotificationManager.IMPORTANCE_DEFAULT

        val channelList = mNotificationManager.notificationChannels
        var i = 0
        while (channelList != null && i < channelList.size) {
            Log.d("channelList","channel ID is ${channelList[i].id}")
            mNotificationManager.deleteNotificationChannel(channelList[i].id)
            i++
        }

        Log.d("isnotification"," is it needed $isNotificationSoundNeeded importance is $importance")
        val mChannel = NotificationChannel(CHANNEL_ID, appName,  NotificationManager.IMPORTANCE_HIGH)
        mChannel.setShowBadge(false)
        mChannel.setSound(notifSound, audioAttributes)



        val mChannelnew = NotificationChannel(CHANNEL_ID2, appName,  NotificationManager.IMPORTANCE_DEFAULT)
        mChannelnew.setShowBadge(false)
        mChannelnew.setSound(notifSound, audioAttributes)




        mNotificationManager.createNotificationChannel(mChannel)

我错过了什么?有什么想法吗?谢谢

更新:以下是notifsound的代码

val notifSound = Uri.parse("android.resource://" + packageName + "/" + R.raw.unconvinced)

你的创建 notifSound 对象的代码在哪里?请注意,卸载/重新安装应用程序不会重置您的通道 - 您需要在应用程序上清除数据。 - ianhanniballake
@ianhanniballake,我已经更新了我的帖子。 - thenewbie
你收到了哪个错误? - Dmitriy Mitiai
如果我使用新的通道,就会出现错误。如果我使用原始通道,它可以工作,但是无法注册任何声音。这太奇怪了。 - thenewbie
3个回答

7

首先我不知道您的通知在哪些设备上无法正常工作,比如OreoPie还是N以下的版本。

对于您的问题,StackOver Flow有很多答案。

现在根据您的问题,您只缺少一行代码,但由于您还没有粘贴整个通知代码,因此无法检查。

这里我粘贴了一段通知代码,可以满足您所有的通知要求。(完全自定义通知

带图片的通知

public void createNotificationWithImage(String title,String message ,Bitmap image) {
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

// Custom Sound Uri

Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
                .getPackageName() + "/" + R.raw.sniper_gun);

 mBuilder = new NotificationCompat.Builder(mContext);
 mBuilder.setSmallIcon(R.mipmap.notification_icon);

 // Pay attention on below line here (NOTE)
 mBuilder.setSound(soundUri);

if (image!=null) {
            mBuilder.setContentTitle(title)
                    .setContentText(message)
                    .setAutoCancel(false)
                    .setLargeIcon(image)
                    .setStyle(new NotificationCompat.BigPictureStyle()
                            .bigPicture(image).setSummaryText(message).bigLargeIcon(null))
                    .setColor(Color.GREEN)
                    .setContentIntent(resultPendingIntent);
        }
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

现在我将粘贴一个通知代码,它可以在OREO设备上运行。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

        if(soundUri != null){
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
            notificationChannel.setSound(soundUri,audioAttributes);
        }

        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());


below middle braces use for close your method.
}

没有图片的通知

    public void createNotification(String title,String message){
    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
                0 /* Request code */, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
                .getPackageName() + "/" + R.raw.sniper_gun);



        mBuilder = new NotificationCompat.Builder(mContext);
        mBuilder.setSmallIcon(R.mipmap.notification_icon);
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),
                R.mipmap.icon));
        mBuilder.setSound(soundUri);
        mBuilder.setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(false)
                .setColor(Color.GREEN)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setContentIntent(resultPendingIntent);

        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//            notificationChannel.s

            if(soundUri != null){
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();
                notificationChannel.setSound(soundUri,audioAttributes);
            }

            assert mNotificationManager != null;
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotificationManager.createNotificationChannel(notificationChannel);

        }

        assert mNotificationManager != null;
        mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

    }

注意:在我的代码中,我提到了一个特定的行,请关注我所描述的设置使用通知时的声音Uri。

mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(soundUri)
            .setColor(Color.GREEN)
            .setStyle(new NotificationCompat.BigTextStyle())
            .setContentIntent(resultPendingIntent);

但是它不会发出声音,因为在Oreo设备中,声音没有被设置为优先级。

因此,始终使用我描述的代码来处理声音。


我不得不像这篇文章一样,将我的音频属性从“通知”类型更改为“闹钟”类型。 - Robert Bentley

1

我猜你正在使用错误的用途类型,请将audioAttributes用途编辑为USAGE_NOTIFICATION

            val audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build()

来自官方文档

USAGE_NOTIFICATION:使用值,当使用为通知时使用。


1
你需要使用音频属性,并且需要定义铃声URI并获得权限。
首先,我们定义铃声URI:
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
boolean vibrate = true;
long[] vibratePattern = new long[]{0L, 1000L};



public constructor(){
 notificationBuilder = new NotificationCompat.Builder(mContext, app.getAppContext().getString(R.string.default_notification_channel_id));
        mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mContext.grantUriPermission("com.android.systemui", ringtoneUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
 public void showNotificationNormal(String notificationTitle, String notificationBody, Intent intent) {
    String id = mContext.getString(R.string.default_notification_channel_id);
    PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
    NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = mContext.getString(R.string.default_notification_channel_name);
        String description = mContext.getString(R.string.default_notification_channel_description); //user visible
        int importance = NotificationManager.IMPORTANCE_HIGH;

        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        mChannel.enableVibration(vibrate);
        mChannel.setVibrationPattern(vibratePattern);
        mChannel.setLightColor(Color.RED);
        mChannel.setSound(ringtoneUri, att);
        mChannel.setBypassDnd(true);
        mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mChannel.setShowBadge(true);

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

        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setVibrate(vibratePattern)
                .setSound(ringtoneUri)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setContentTitle(notificationTitle)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody))
                .setAutoCancel(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(lowIntent);

    } else {
        notificationBuilder.setContentTitle(notificationTitle)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setVibrate(vibratePattern)
                .setSound(ringtoneUri)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody))
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setAutoCancel(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(lowIntent);

    }

    notificationBuilder.setContentText(notificationBody);

    if (mNotifyManager != null) {
        mNotifyManager.notify(AppConstants.NOTIFY_ID, notificationBuilder.build());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接