安卓通知声音

169

我已经使用了更新的NotificationCompat构建器,但是无法让通知发出声音。它会振动和闪烁灯光。 Android文档说要设置样式,我已经这样做了:

我已经使用了更新的NotificationCompat构建器,但是不能让通知发出声音。它可以震动和闪烁灯光。Android文档建议设置一个样式,我已经按照下面的方式设置:

builder.setStyle(new NotificationCompat.InboxStyle());

但是没有声音吗?

完整的代码:

NotificationCompat.Builder builder =  
        new NotificationCompat.Builder(this)  
        .setSmallIcon(R.drawable.ic_launcher)  
        .setContentTitle("Notifications Example")  
        .setContentText("This is a test notification");  


Intent notificationIntent = new Intent(this, MenuScreen.class);  

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
        PendingIntent.FLAG_UPDATE_CURRENT);  

builder.setContentIntent(contentIntent);  
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
// Add as notification  
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
manager.notify(1, builder.build());  

15
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) 也可以起作用。 - Zar E Ahmer
20个回答

271

我之前的代码缺少了什么:

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

4
它一直响个不停,怎么才能让它只响一次? 使用 builder.setOnlyOnce(true); 没有效果。 - Salis
它只会播放一次。 - blackHawk
4
在我的情况下,builder.setOnlyOnce(true)解决了我的问题! - ElOjcar

167

只需将您的声音文件放置在Res\raw\siren.mp3文件夹中,然后使用以下代码:

用于自定义声音:

Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
            + context.getPackageName() + "/" + R.raw.siren);

默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;

自定义震动:

long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;

默认震动:

notification.defaults |= Notification.DEFAULT_VIBRATE;

55

默认声音的另一种方式

builder.setDefaults(Notification.DEFAULT_SOUND);

14

在 Oreo(Android 8)及以上版本中,应该通过以下方式进行自定义通知声音设置(通知通道):

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

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

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);

13

使用Can Codeding

 String en_alert, th_alert, en_title, th_title, id;
 int noti_all, noti_1, noti_2, noti_3, noti_4 = 0, Langage;

 class method
 Intent intent = new Intent(context, ReserveStatusActivity.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

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


 intent = new Intent(String.valueOf(PushActivity.class));
 intent.putExtra("message", MESSAGE);
 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
 stackBuilder.addParentStack(PushActivity.class);
 stackBuilder.addNextIntent(intent);
 // PendingIntent pendingIntent =
 stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

 //      android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
 //        bigStyle.bigText((CharSequence) context);



 notification = new NotificationCompat.Builder(context)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle(th_title)
    .setContentText(th_alert)
    .setAutoCancel(true)

 // .setStyle(new Notification.BigTextStyle().bigText(th_alert)  ตัวเก่า
 //

 .setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))

    .setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))

    .setContentIntent(pendingIntent)
    .setNumber(++numMessages)


    .build();

 notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

 notificationManager.notify(1000, notification);

10

只需将下面的简单代码放入:

notification.sound = Uri.parse("android.resource://"
        + context.getPackageName() + "/" + R.raw.sound_file);

默认音效:

notification.defaults |= Notification.DEFAULT_SOUND;

10
你需要使用RingtoneManager
private static final int MY_NOTIFICATION_ID = 1;
    private NotificationManager notificationManager;
    private Notification myNotification;

    private final String myBlog = "http://niravranpara.blogspot.com/";

使用闹钟铃声的通知管理器代码,你也可以设置铃声为RingtoneManager.TYPE_RINGTONE。

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri
                        .parse(myBlog));
                  PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Notification note = new Notification(R.drawable.ic_launcher, "Alarm", System.currentTimeMillis());
                    note.setLatestEventInfo(getApplicationContext(), "Alarm", "sound" + " (alarm)", pi);
                    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                    if(alarmSound == null){
                        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        if(alarmSound == null){
                            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        }
                    }
                    note.sound = alarmSound;
                    note.defaults |= Notification.DEFAULT_VIBRATE;
                    note.flags |= Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(MY_NOTIFICATION_ID, note);

抱歉,这不是适用于较新的NotificationCompat.Builder的方法。 - James MV
可以使用NotificationCompat.Builder.build()函数来创建通知,并且在将其传递给NotificationManager.notify之前,修改build()的返回值是可以的。这样做虽然没有太多意义,但完全没有问题。 - holgac

8
在 Android OREO 或更高版本中, enter image description here 注册通道后; 在卸载应用之前, 您无法更改同一通道的重要性或其他通知行为。
private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);

优先级也很重要 使用以下方法将通知优先级设置为高

用户可见的重要性水平 重要度 (Android 8.0 及更高版本)

1)紧急 发出声音并显示为弹出式通知--> IMPORTANCE_HIGH
2)高 发出声音--> IMPORTANCE_DEFAULT
3)中 无声音--> IMPORTANCE_LOW
4)低 无声音且不会在状态栏中显示--> IMPORTANCE_MIN

相同工作以相同顺序进行 优先级 (Android 7.1及以下版本)

1)PRIORITY_HIGH或PRIORITY_MAX

2)PRIORITY_DEFAULT

3)PRIORITY_LOW

4)PRIORITY_MIN


3
你不能在同一频道之后更改其重要性或其他通知行为”。需要卸载应用才能使其正常工作,但这将导致设备中该频道的信息被删除。 - Ely Dantas

8
您可以创建一个函数:
public void playNotificationSound() 
{
    try
    {

        Uri alarmSound = `Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.getInstance().getApplicationContext().getPackageName() + "/raw/notification");`
        Ringtone r = RingtoneManager.getRingtone(MyApplication.getInstance().getApplicationContext(), alarmSound);
        r.play();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

当您收到通知时,请调用此函数。

这里的"raw"是在资源文件夹中的一个文件夹,而通知声音文件则在"raw"文件夹中。


6

您需要使用构建器 setSound

该方法可用于设置通知的提示音。

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

                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,   
                        PendingIntent.FLAG_UPDATE_CURRENT);  

                builder.setContentIntent(contentIntent);  
                builder.setAutoCancel(true);
                builder.setLights(Color.BLUE, 500, 500);
                long[] pattern = {500,500,500,500,500,500,500,500,500};
                builder.setVibrate(pattern);
                builder.setStyle(new NotificationCompat.InboxStyle());
                 Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                    if(alarmSound == null){
                        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        if(alarmSound == null){
                            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        }
                    }

                // Add as notification  
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
             builder.setSound(alarmSound);
                manager.notify(1, builder.build());  

1
你重复了两次写RingtoneManager.TYPE_RINGTONE。 - Bernardo Ferrari

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