通知的振动和声音默认设置

100

我想在通知到来时设置默认的震动和声音提醒,但是目前还没有成功。我想这可能与我设置默认方式有关,但我不确定如何解决。有什么想法吗?

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

}

3
所有的回答都只是重申了你已经有的代码的某种变化,我认为它们都没有回答这个问题。据我所知,你的代码看起来很好。最有可能的情况是,在AndroidManifest.xml中你只是缺少了android.permission.VIBRATE权限。 - Olaf Dietsche
适用于本帖解决方案但仍未收到通知震动的用户,您可能需要先启用通知渠道的震动。请参考以下链接:https://dev59.com/sqXja4cB1Zd3GeqPRHG_#47646166 - Mostafa Arian Nejad
9个回答

219

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

   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" />

117
+1vibrate 功能需要 <uses-permission android:name="android.permission.VIBRATE" /> 权限。 - ashakirov
1
在某些情况下,你应该使用十六进制的 argb 格式,如 0xffffffff,而不是 Color.White,因为存在用户设备使用 Color(RGB)用于 ARGB 参数的可能性很小,这样你会得到错误的颜色。我曾经遇到过这种情况。 - Beto Caldas
60
现在的震动有1000毫秒的延迟。如果你把第一个设置为0,它将立即触发。这是一个“{延迟,震动,休眠,震动,休眠}”的模式。 - Tom
11
我不需要添加 <uses-permission android:name="android.permission.VIBRATE" /> 就可以工作。 - Iqbal
1
有人知道如何在API 26上使用setSound吗? - Rodrigo Manguinho

61

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

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


37

通知 震动

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

声音

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

了解更多声音选项


3
对于振动功能,确保在AndroidManifest.xml文件中包含<uses-permission android:name="android.permission.VIBRATE" /> - Aaron Esau
这个震动会持续多久?还是只会震动一次? - Zapnologica

14

它对我来说很好用,你可以试试。

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

    }

10

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

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"/>

祝你好运,'.


有人能告诉我为什么在通话中时振动功能无法使用吗?或者我们可以制作一个通知,在电话通话中也能强制震动吗? - user526206
它帮助了我 notificationBuilder.setDefaults(notification.defaults); - Saveen
@user526206,我不知道。我从未测试过那个问题。您可以提出新的问题,因为这与通知行为无关。 - Maher Abuthraa

7
我正在使用以下代码,它对我来说工作得很好。
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.");
}

5
为支持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


2
对于Kotlin,您可以尝试这个。
var builder = NotificationCompat.Builder(this,CHANNEL_ID)
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

2

// 设置通知音频

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

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