Вибрация и звук по умолчанию при уведомлении


93

Я пытаюсь установить вибрацию и звуковое оповещение по умолчанию, когда приходит мое уведомление, но пока безуспешно. Я предполагаю, что это как-то связано с тем, как я установил значения по умолчанию, но я не уверен, как это исправить. Есть предположения?

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
Все ответы лишь повторяют некоторые варианты кода, который у вас уже есть, и, на мой взгляд, ни один из них не отвечает на вопрос. Ваш код выглядит нормально, AFAICT. Скорее всего, вам просто не хватает android.permission.VIBRATEAndroidManifest.xml.
— Olaf Dietsche

Кому это может применить решения в этой ветке и по-прежнему не имеет никакой вибрации при уведомлениях, вам может потребоваться сначала включить вибрацию вашего канала уведомлений. Взгляните на это: stackoverflow.com/a/47646166/8551764
— Мостафа Ариан Неджад

Ответы:


204

Некоторые фиктивные коды могут вам помочь.

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

115
+1 vibrateфункция требует <uses-permission android:name="android.permission.VIBRATE" />разрешения
— ашакиров

1
В некоторых случаях вам следует использовать шестнадцатеричный цветовой формат argb, например 0xffffffff, вместо Color.White, потому что существует небольшая вероятность того, что пользовательское устройство будет использовать Color (RGB) для параметра ARGB, и вы получите неправильный цвет. Это случилось со мной.
— Бето Калдас,

55
Теперь задержка вибрации составляет 1000 мс. Если вы установите для первого значение 0, он мгновенно сработает. Это шаблон {задержка, вибрация, сон, вибрация, сон}.
— Том

11
Мне не нужно было ничего добавлять <uses-permission android:name="android.permission.VIBRATE" />к работе.
— Икбал

1
Кто-нибудь знает, как использовать setSound в API 26?
— Родриго

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

Это даст вам звук уведомления по умолчанию.


35

Уведомление Вибрация

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

Звук

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

для более звукового варианта


2
Для вибросигнала обязательно <uses-permission android:name="android.permission.VIBRATE" />включите в свой AndroidManifest.xml
— Аарон Исау

как долго длится эта вибрация? или он просто один раз завибрирует?
— Zapnologica

13

Мне это нравится, вы можете попробовать.

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

Удачи,'.


Может кто подскажет, почему не работает вибрация при звонке телефона? ИЛИ можем ли мы сделать уведомление, чтобы заставить вибрировать, даже когда телефон находится в состоянии вызова

Мне помогло notificationBuilder.setDefaults (notification.defaults);
— Saveen

@ user526206, не знаю. Я никогда этого не проверял. Вы можете открыть новый вопрос, поскольку он не имеет ничего общего с поведением уведомлений.
— Махер Абутраа

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.");
}


1

Для Котлина вы можете попробовать это.

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

1

Для поддержки версии 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сделали правильный выбор, чтобы узнать больше здесь .

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.