【问题标题】:Vibrate and Sound defaults on notification通知的振动和声音默认设置
【发布时间】:2013-08-17 16:32:46
【问题描述】:

我正在尝试在收到通知时获得默认的振动和声音警报,但到目前为止还没有成功。我想这与我设置默认值的方式有关,但我不确定如何修复它。有什么想法吗?

public void connectedNotify() {
    Integer mId = 0;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

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

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =     
          PendingIntent.getActivity(getApplicationContext(), 
          0, 
          resultIntent,  
          PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setOngoing(true);
    Notification note = mBuilder.build();
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mId, note);

}

【问题讨论】:

  • 所有答案都只是重申了您已经拥有的代码的一些变体,在我看来,他们都没有回答这个问题。你的代码看起来不错,AFAICT。很可能,您只是在 AndroidManifest.xml 中缺少 android.permission.VIBRATE。
  • 谁可以在此线程中应用解决方案,但通知仍然没有任何振动,您可能需要先启用通知通道的振动。看看这个:stackoverflow.com/a/47646166/8551764

标签: android


【解决方案1】:

一些虚拟代码可能会对您有所帮助。

   private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
            .setWhen(System.currentTimeMillis()).......;
     //Vibration
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

     //LED
        builder.setLights(Color.RED, 3000, 3000);

     //Ton
        builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

    return builder;
   }

在AndroidManifest.xml 文件中添加以下振动权限

<uses-permission android:name="android.permission.VIBRATE" />

【讨论】:

  • +1 vibrate 功能需要&lt;uses-permission android:name="android.permission.VIBRATE" /&gt; 权限
  • 在某些情况下,您应该使用十六进制颜色 argb 格式,例如 0xffffffff,而不是 Color.White,因为用户设备使用 Color(RGB) 作为 ARGB 参数的可能性很小,您会得到错误的颜色。这发生在我身上。
  • 振动现在有 1000 毫秒的延迟。如果将第一个设置为 0,它将立即关闭。这是一种{延迟、振动、睡眠、振动、睡眠}模式。
  • 我不需要添加&lt;uses-permission android:name="android.permission.VIBRATE" /&gt; 来工作。
  • 有人知道如何在 API 26 上使用 setSound 吗?
【解决方案2】:

TeeTracker 答案的扩展,

要获得默认通知声音,您可以执行以下操作

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

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

这将为您提供默认通知声音。

【讨论】:

    【解决方案3】:

    通知 振动

    mBuilder.setVibrate(new long[] { 1000, 1000});
    

    声音

    mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
    

    for more sound option

    【讨论】:

    • 对于振动器,请务必在您的 AndroidManifest.xml 中包含 &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;
    • 这种振动持续多长时间?还是只会振动一次?
    【解决方案4】:

    对我来说效果很好,你可以试试。

     protected void displayNotification() {
    
            Log.i("Start", "notification");
    
          // Invoking the default notification service //
            NotificationCompat.Builder  mBuilder =
                    new NotificationCompat.Builder(this);
            mBuilder.setAutoCancel(true);
    
            mBuilder.setContentTitle("New Message");
            mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
            mBuilder.setTicker("New message from PayMe..");
            mBuilder.setSmallIcon(R.drawable.icon2);
    
          // Increase notification number every time a new notification arrives //
            mBuilder.setNumber(unMber_unRead_sms);
    
          // Creates an explicit intent for an Activity in your app //
    
            Intent resultIntent = new Intent(this, FreesmsLog.class);
    
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(FreesmsLog.class);
    
          // Adds the Intent that starts the Activity to the top of the stack //
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(
                            0,
                            PendingIntent.FLAG_UPDATE_CURRENT
                    );
            mBuilder.setContentIntent(resultPendingIntent);
    
          //  mBuilder.setOngoing(true);
            Notification note = mBuilder.build();
            note.defaults |= Notification.DEFAULT_VIBRATE;
            note.defaults |= Notification.DEFAULT_SOUND;
    
            mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          // notificationID allows you to update the notification later on. //
            mNotificationManager.notify(notificationID, mBuilder.build());
    
        }
    

    【讨论】:

      【解决方案5】:

      这是一种使用系统默认振动和声音来调用通知的简单方法。

      private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
          Intent intent = new Intent(this, MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                  PendingIntent.FLAG_ONE_SHOT);
          Notification notification = new Notification();
      
          NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
      
          if (sound) {
              notification.defaults |= Notification.DEFAULT_SOUND;
          }
      
          if (vibrate) {
              notification.defaults |= Notification.DEFAULT_VIBRATE;
          }
      
          notificationBuilder.setDefaults(notification.defaults);
          notificationBuilder.setSmallIcon(iconID)
                  .setContentTitle(title)
                  .setContentText(message)
                  .setAutoCancel(true)
                  .setTicker(tick)
                  .setContentIntent(pendingIntent);
      
          NotificationManager notificationManager =
                  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      
          notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
      }
      

      如果您要使用它,请添加振动权限:

      <uses-permission android:name="android.permission.VIBRATE"/>
      

      祝你好运,'。

      【讨论】:

      • 有人能告诉我为什么打电话时振动不起作用吗?或者我们可以发出通知以强制振动,即使在电话正在通话中
      • 它帮助了我 notificationBuilder.setDefaults(notification.defaults);
      • @user526206,我不知道。我从来没有测试过。您可以打开新问题,因为这与通知行为无关。
      【解决方案6】:

      我正在使用以下代码,它对我来说工作正常。

      private void sendNotification(String msg) {
          Log.d(TAG, "Preparing to send notification...: " + msg);
          mNotificationManager = (NotificationManager) this
                  .getSystemService(Context.NOTIFICATION_SERVICE);
      
          PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                  new Intent(this, MainActivity.class), 0);
      
          NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                  this).setSmallIcon(R.drawable.ic_launcher)
                  .setContentTitle("GCM Notification")
                  .setAutoCancel(true)
                  .setDefaults(Notification.DEFAULT_ALL)
                  .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                  .setContentText(msg);
      
          mBuilder.setContentIntent(contentIntent);
          mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
          Log.d(TAG, "Notification sent successfully.");
      }
      

      【讨论】:

        【解决方案7】:

        要支持 SDK 版本 >= 26,您还应该构建 NotificationChanel 并在其中设置振动模式和声音。有一个 Kotlin 代码示例:

            val vibrationPattern = longArrayOf(500)
            val soundUri = "<your sound uri>"
        
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val notificationManager =    
                         getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                    val attr = AudioAttributes.Builder()
                                .setUsage(AudioAttributes.USAGE_ALARM)
                                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                                .build()
                    val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
                    val importance = NotificationManager.IMPORTANCE_HIGH
                    val notificationChannel =
                        NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
                        notificationChannel.enableLights(true)
                        notificationChannel.lightColor = Color.RED
                        notificationChannel.enableVibration(true)
                        notificationChannel.setSound(soundUri, attr)
                        notificationChannel.vibrationPattern = vibrationPattern
                        notificationManager.createNotificationChannel(notificationChannel)
            }
        

        这是建造者:

         with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
                setContentTitle("Some title")
                setContentText("Some content")
                setSmallIcon(R.drawable.ic_logo)
                setAutoCancel(true)    
                setVibrate(vibrationPattern)
                setSound(soundUri)
                setDefaults(Notification.DEFAULT_VIBRATE)
                setContentIntent(
                    // this is an extension function of context you should build
                    // your own pending intent and place it here
                    createNotificationPendingIntent(
                        Intent(applicationContext, target).apply {
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        }
                    )
                )
        
                return build()
            }
        

        确保您的AudioAttributes 被正确选择以阅读更多here。

        【讨论】:

          【解决方案8】:

          //设置通知音频

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

          【讨论】:

            【解决方案9】:

            对于 Kotlin,你可以试试这个。

            var builder = NotificationCompat.Builder(this,CHANNEL_ID)
                 .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
                 .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-02-10
              • 1970-01-01
              • 1970-01-01
              • 2012-07-01
              • 1970-01-01
              相关资源
              最近更新 更多