164

我使用了较新的 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());  
4

18 回答 18

267

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

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
于 2013-04-06T20:06:23.103 回答
164

只需将您的声音文件放在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;
于 2013-08-01T12:11:34.470 回答
55

默认声音的另一种方式

builder.setDefaults(Notification.DEFAULT_SOUND);
于 2014-12-05T05:41:46.153 回答
13

使用罐头编码

 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);
于 2015-09-23T07:57:17.100 回答
13

在 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);
于 2018-09-18T20:35:37.393 回答
10

只需输入以下简单代码:

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

对于默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;
于 2013-09-07T04:59:15.230 回答
9

你必须使用RingtoneManager

private static final int MY_NOTIFICATION_ID = 1;
    private NotificationManager notificationManager;
    private Notification myNotification;

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

带有闹钟铃声的 noficationmanager 代码,您还可以设置铃声 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);
于 2013-04-04T11:39:40.323 回答
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 是 res 中的文件夹,而 notification 是 raw 文件夹中的声音文件。

于 2017-05-08T08:03:11.247 回答
7

在 Android OREO 或更高版本 系统中注册频道后;在此之后,您无法更改同一频道的重要性其他通知行为 (卸载应用程序之前)在此处输入图像描述

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);

优先级也很重要 Most Here通过使用 将通知优先级设置为高

用户可见的重要性级别重要性(Android 8.0 及更高版本)

1)Urgent 发出声音并显示为提醒通知--> IMPORTANCE_HIGH
2)High 发出声音-> IMPORTANCE_DEFAULT
3)Medium 无声音-> IMPORTANCE_LOW
4)Low无声音且不出现在状态栏中-> IMPORTANCE_MIN

相同的工作顺序 优先级(Android 7.1 及更低版本)

1)PRIORITY_HIGH 或 PRIORITY_MAX

2)PRIORITY_DEFAULT

3)PRIORITY_LOW

4)PRIORITY_MIN

于 2019-04-10T08:00:20.153 回答
6

你必须使用生成器。设置声音

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());  
于 2013-04-08T06:24:03.630 回答
5

首先将“yourmp3file”.mp3 文件放入原始文件夹(即在 Res 文件夹中)

第二在你的代码放..

Notification noti = new Notification.Builder(this)
.setSound(Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.yourmp3file))//*see note

这就是我放在 onClick(View v) 中的内容,因为只有“context().getPackageName()”不会从那里工作,因为它不会获得任何上下文

于 2015-12-01T14:42:50.257 回答
4
private void showNotification() {

    // intent triggered, you can add other intent for other actions
    Intent i = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, i, 0);

    //Notification sound
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {

        mNotification = new Notification.Builder(this)

           .setContentTitle("Wings-Traccar!")
           .setContentText("You are punched-in for more than 10hrs!")
           .setSmallIcon(R.drawable.wingslogo)
           .setContentIntent(pIntent)
           .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
           .addAction(R.drawable.favicon, "Goto App", pIntent)
           .build();

    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}

在任何你想要的地方调用这个函数。这对我有用

于 2018-12-26T10:04:43.487 回答
1
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
于 2015-08-14T02:55:52.720 回答
0

通过下面给出的 Notification.builder 类实例(builder),您可以在通知上播放默认声音:

builder.setDefaults(Notification.DEFAULT_SOUND);
于 2018-07-09T13:52:19.087 回答
0

// 设置通知音频(测试到 android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);
于 2019-10-30T18:16:52.683 回答
0
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    btn= findViewById(R.id.btn); 

   btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            notification();
        }
    });
  }   



private void notification() {
    NotificationCompat.Builder builder= new 
    NotificationCompat.Builder(this);
    builder.setAutoCancel(true);
    builder.setContentTitle("Work Progress");
    builder.setContentText("Submit your today's work progress");
    builder.setSmallIcon(R.drawable.ic_email_black_24dp);
    Intent intent=new Intent(this, WorkStatus.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, 
    PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    builder.setDefaults(Notification.DEFAULT_VIBRATE);
    builder.setDefaults(Notification.DEFAULT_SOUND);

    NotificationManager notificationManager= (NotificationManager) 
    getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());
}

它是带有声音和振动的完整通知

于 2019-12-17T05:58:03.287 回答
0

不要依赖于构建器或通知。使用自定义代码进行振动。

public static void vibrate(Context context, int millis){
    try {
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            v.vibrate(millis);
        }
    }catch(Exception ex){
    }
}
于 2020-05-19T23:38:36.623 回答
-1

您可以执行以下操作:

MediaPlayer mp;
mp =MediaPlayer.create(Activity_Order_Visor_Atender.this, R.raw.ok);         
mp.start();

你在你的资源之间创建了一个名为 raw 的包,并在那里保留你的声音,然后你就调用它。

于 2018-04-12T21:56:24.957 回答