【问题标题】:Android Notification Sound安卓通知声音
【发布时间】:2013-04-04 11:06:01
【问题描述】:

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

【问题讨论】:

  • builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) 也应该可以工作

标签: android android-notifications


【解决方案1】:

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

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

【讨论】:

  • 它一直在播放并且不会停止,我如何让它只响一次?使用 builder.setOnlyOnce(true);没有帮助
  • 一次性播放
  • builder.setOnlyOnce(true) 解决了我的问题!
【解决方案2】:

只需将您的声音文件放在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;

【讨论】:

    【解决方案3】:

    默认声音的另一种方式

    builder.setDefaults(Notification.DEFAULT_SOUND);
    

    【讨论】:

      【解决方案4】:

      使用可以编码

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          只需输入以下简单代码:

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

          对于默认声音:

          notification.defaults |= Notification.DEFAULT_SOUND;
          

          【讨论】:

            【解决方案7】:

            你必须使用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);
            

            【讨论】:

            • 抱歉,这不是您为较新的 NotificationCompat.Builder 执行此操作的方式。
            • 可以使用 NotificationCompat.Builder.build() 函数创建通知,并且可以在传递给 NotificationManager.notify 之前获取 build() 的返回值并修改其值。没有多大意义,但完全没问题。
            【解决方案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 文件夹中的声音文件。

            【讨论】:

              【解决方案9】:

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

              优先级也很重要 使用

              将通知优先级设置为高

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

              1)紧急 发出声音并显示为提醒通知-->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

              【讨论】:

              • "在此之后您不能更改同一频道的重要性或其他通知行为"。需要卸载应用才能正常工作,此操作从设备中删除了频道信息。
              【解决方案10】:

              你必须使用builder.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());  
              

              【讨论】:

              • 你写了两次 RingtoneManager.TYPE_RINGTONE。
              【解决方案11】:

              首先将“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()”无法从那里工作,因为它不会获得任何上下文

              【讨论】:

                【解决方案12】:
                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);
                }
                

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

                【讨论】:

                  【解决方案13】:
                  notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                  

                  【讨论】:

                    【解决方案14】:

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

                    builder.setDefaults(Notification.DEFAULT_SOUND);
                    

                    【讨论】:

                      【解决方案15】:

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

                      builder.setDefaults(Notification.DEFAULT_VIBRATE);
                      //OR 
                      builder.setDefaults(Notification.DEFAULT_SOUND);
                      

                      【讨论】:

                        【解决方案16】:

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

                        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){
                            }
                        }
                        

                        【讨论】:

                          【解决方案17】:
                          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());
                          }
                          

                          这是完整的声音和振动通知

                          【讨论】:

                            【解决方案18】:

                            您可以执行以下操作:

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

                            您在资源之间创建一个名为 raw 的包,然后将声音保存在那里,然后调用它。

                            【讨论】:

                              猜你喜欢
                              • 2011-05-25
                              • 2018-11-18
                              • 1970-01-01
                              • 1970-01-01
                              • 2013-04-23
                              • 2011-08-02
                              • 1970-01-01
                              • 2014-06-20
                              相关资源
                              最近更新 更多