За замовчуванням вібрувати та звучати в сповіщенні


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.VIBRATEв AndroidManifest.xml.
Олаф Дієтше

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

Відповіді:


203

Деякі фіктивні коди можуть вам допомогти.

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

114
Для vibrateфункції +1 потрібен <uses-permission android:name="android.permission.VIBRATE" />дозвіл
ashakirov

1
У деяких випадках замість Color.White слід використовувати формат argb у шістнадцятковому кольорі, наприклад 0xffffffff, оскільки існує невелика ймовірність використання користувачем пристрою Color (RGB) для параметра ARGB, і ви отримаєте неправильний колір. Це сталося зі мною.
Beto Caldas

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

Удачі,'.


Хтось може сказати мені, чому вібрація не працює, коли телефон телефонує? АБО ми можемо зробити сповіщення про примусовий вібросигнал, навіть коли телефонний дзвінок

Це допомогло мені уведомлениеBuilder.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.");
}

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 і встановити там вібраційний шаблон і звук. Існує зразок коду Котліна:

    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.