自定义通知声音在 Android Oreo 中不起作用

Posted

技术标签:

【中文标题】自定义通知声音在 Android Oreo 中不起作用【英文标题】:Custom Notification Sound not working in Android Oreo 【发布时间】:2018-11-07 02:15:44 【问题描述】:
Uri sound = Uri.parse(ContentResolver.SCHEME_android_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
            mBuilder.setSound(sound);

我已将 mp3 (notification_mp3.mp3) 文件复制到 res 文件夹中的 raw 文件夹中。当通知被触发时,它会在 Android Nougat 中产生给定的 mp3 声音,但在 Android Oreo 中产生默认声音。 我推荐了很多网站,但在 Android Oreo 上没有任何效果。我在 Android Docs 中没有发现关于 Android O 及更高版本通知声音的任何变化。 应该进行哪些更改才能使此代码也能在 Android O 中运行?

【问题讨论】:

您在 Android 8.0+ 中设置了通知通道上的声音,而不是通知上的声音。 【参考方案1】:

要在 Oreo 中为通知设置声音,您必须在 NotificationChannel 而不是 Notification Builder 本身上设置声音。你可以这样做

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 

        NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
            "YOUR CHANNEL NAME",
            NotificationManager.IMPORTANCE_DEFAULT)

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, 
                context.getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        mChannel.setDescription(msg);
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setSound(sound, attributes); // This is IMPORTANT


        if (mNotificationManager != null)
            mNotificationManager.createNotificationChannel(mChannel);
    

这将为您的通知设置自定义声音。但是如果应用正在更新,并且之前使用了通知渠道,则不会更新。即您需要创建一个不同的频道并为其设置声音以使其正常工作。但这将在您的应用的应用信息的通知部分显示多个频道。如果您将声音设置为一个全新的通道,这很好,但如果您希望之前使用该通道,则必须删除现有通道并重新创建该通道。为此,您可以在创建频道之前执行类似的操作

if (mNotificationManager != null) 
            List<NotificationChannel> channelList = mNotificationManager.getNotificationChannels();

            for (int i = 0; channelList != null && i < channelList.size(); i++) 
                mNotificationManager.deleteNotificationChannel(channelList.get(i).getId());
            
        

【讨论】:

它工作得很好,但只有当应用程序处于前台时。当应用程序处于后台(对于奥利奥)时,我仍然有默认声音。你有解决方案吗? 看看这个答案***.com/a/37845174/2577750 是的,我们需要发送数据消息,谢谢 Ankush,这有帮助 删除后创建通知通道时,系统只使用旧的通道设置。任何人已经能够使用上述方法更改通知通道的声音,如果还有什么需要做的,您可以评论一下。 别忘了你需要重新安装应用程序,否则它会以某种方式回收旧的通知渠道【参考方案2】:

这可能会对新来者有所帮助。

这是一个适用于所有 Android 版本以及各种可能设置的工作通知示例的代码。

1 -> sound and vibration
2 -> sound but no vibration
3 -> no sound but vibration
4 -> no sound no vibration

输出

Github 回购 -> https://github.com/usman14/Notification

代码

主活动

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity 

    public boolean shouldSound;
    public boolean shouldVibrate;
    NotificationManager notificationManager;

    Button button;
    Switch soundSwitch;
    Switch vibrationSwitch;

    @TargetApi(Build.VERSION_CODES.O)
    public void registerNormalNotificationChannel(android.app.NotificationManager notificationManager) 

        NotificationChannel channel_all = new NotificationChannel("CHANNEL_ID_ALL", "CHANNEL_NAME_ALL", NotificationManager.IMPORTANCE_HIGH);
        channel_all.enableVibration(true);
        notificationManager.createNotificationChannel(channel_all);

        NotificationChannel channel_sound = new NotificationChannel("CHANNEL_ID_SOUND", "CHANNEL_NAME_ALL", NotificationManager.IMPORTANCE_HIGH);
        channel_sound.enableVibration(false);
        notificationManager.createNotificationChannel(channel_sound);

        NotificationChannel channel_vibrate = new NotificationChannel("CHANNEL_ID_VIBRATE", "CHANNEL_NAME_ALL", NotificationManager.IMPORTANCE_HIGH);
        channel_vibrate.setSound(null, null);
        channel_vibrate.enableVibration(true);
        notificationManager.createNotificationChannel(channel_vibrate);


        NotificationChannel channel_none = new NotificationChannel("CHANNEL_ID_NONE", "CHANNEL_NAME_ALL", NotificationManager.IMPORTANCE_HIGH);
        channel_none.setSound(null, null);
        channel_none.enableVibration(false);
        notificationManager.createNotificationChannel(channel_none);
    

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btn);
        soundSwitch = findViewById(R.id.switch_sound);
        vibrationSwitch = findViewById(R.id.switch_vibration);
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (isOreoOrAbove()) 
            setupNotificationChannels();
        

        button.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                makeNotification();
            
        );

        soundSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) 
                if (b) 
                    shouldSound = true;
                 else 
                    shouldSound = false;
                
            
        );

        vibrationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) 
                if (b) 
                    shouldVibrate = true;
                 else 
                    shouldVibrate = false;
                
            
        );
    

    private void setupNotificationChannels() 
        registerNormalNotificationChannel(notificationManager);
    

    public void makeNotification() 
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, getChannelId())
                .setContentTitle("Hi")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("Welcome to Android");

        Intent intent = new Intent(MainActivity.this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        if (shouldSound && !shouldVibrate) 
            builder.setDefaults(Notification.DEFAULT_SOUND)
                    .setVibrate(new long[]0L);
        
        if (shouldVibrate && !shouldSound) 
            builder.setDefaults(Notification.DEFAULT_VIBRATE)
                    .setSound(null);
        
        if (shouldSound && shouldVibrate) 
            builder.setDefaults(Notification.DEFAULT_ALL);
        


        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, builder.build());
    

    private String getChannelId() 
        if (shouldSound && shouldVibrate) 
            return "CHANNEL_ID_ALL";
         else if (shouldSound && !shouldVibrate) 
            return "CHANNEL_ID_SOUND";
         else if (!shouldSound && shouldVibrate) 
            return "CHANNEL_ID_VIBRATE";
         else 
            return "CHANNEL_ID_NONE";
        
    

    private boolean isOreoOrAbove() 
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O;
    

activity_main (xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MainActivity">



    <LinearLayout
        android:layout_
        android:layout_
        android:gravity="center"
        android:id="@+id/sound_layout"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <TextView
            android:layout_
            android:layout_
            android:text="SOUND SWITCH"></TextView>


        <Switch
            android:layout_marginLeft="50dp"
            android:layout_
            android:layout_
            android:layout_gravity="center_vertical"
            android:id="@+id/switch_sound">

        </Switch>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/vibration_layout"
        android:layout_
        android:layout_
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/sound_layout">

        <TextView
            android:layout_
            android:layout_
            android:text="VIBRATION SWITCH"></TextView>


        <Switch
            android:layout_marginLeft="50dp"
            android:layout_
            android:layout_
            android:layout_gravity="center_vertical"
            android:id="@+id/switch_vibration">

        </Switch>

    </LinearLayout>


    <Button
        android:layout_
        android:layout_
        android:text="Send Notification"
        android:id="@+id/btn"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/vibration_layout"></Button>

</androidx.constraintlayout.widget.ConstraintLayout>

【讨论】:

【参考方案3】:

创建频道(我在Application.clss使用这个方法创建频道)

  public void initChannels(Context context) 
    if (Build.VERSION.SDK_INT < 26) 
        return;
    
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default"/*CHANNEL ID*/,
            "CHANNEL_NAME",
            NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    assert notificationManager != null;
    notificationManager.createNotificationChannel(channel);

并在创建NotificationCompat 的实例时使用此频道default

 .... notificationBuilder = new NotificationCompat.Builder(this,"default") ....

【讨论】:

【参考方案4】:

Android O 自带 NotificationChannel 来代替

 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);
            assert mNotificationManager != null;
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotificationManager.createNotificationChannel(notificationChannel);

【讨论】:

mNotificationManagermNotificationManager 声明在哪里? 自定义声音在哪里?这没有回答问题。【参考方案5】:
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)

这行代码对我有用。但是您必须删除旧频道并创建新频道。

【讨论】:

【参考方案6】:

你好,Mates首先使用设备默认的通知声音,添加以下内容。

Uri uri = getDefaultUri(TYPE_NOTIFICATION); // To get the URI of default notification uri
AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();

然后,抱歉,这听起来可能很愚蠢。但您还需要确保设备的默认通知和声音设置为非无。我相信这很容易被忽视。

欢呼!

【讨论】:

【参考方案7】:

注释可能有助于模拟器测试。

不要忘记启用如下突出显示的警报声音:-

【讨论】:

【参考方案8】:

试试这个:

/**
 * show notification
 *
 * @param message
 */
private static void showNotification(RemoteMessage message, Context baseContext) 
    Context context = baseContext.getApplicationContext();
    NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context.getApplicationContext());
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, null)
            .setSmallIcon(R.drawable.ic_logo_xxxdpi)
            .setContentTitle(message.getData().get(TITLE))
            .setContentText(message.getData().get(BODY))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setVibrate(new long[]500, 500)
            .setLights(Color.RED, 3000, 3000)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(getPendingIntent(context, message));
    managerCompat.notify(getRandom(), builder.build());

【讨论】:

这行不通,因为您应该使用通知渠道。

以上是关于自定义通知声音在 Android Oreo 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Monaca:使用 Onesignal 在 Android 中自定义通知声音和小图标

为啥 Galaxy S21 没有自定义通知声音

手机进入睡眠状态时不播放自定义通知声音

FCM 通知在 OREO 中不起作用

如何使用 FCM 在 ios 推送通知中播放自定义通知声音

Ionic 3 本地通知 LED/声音在 Android 中不起作用