Vibreur et son par défaut lors de la notification


93

J'essaie d'obtenir un vibreur et une alerte sonore par défaut lorsque ma notification arrive, mais jusqu'à présent, pas de chance. J'imagine que cela a quelque chose à voir avec la façon dont j'ai défini les paramètres par défaut, mais je ne sais pas comment y remédier. Des pensées?

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
Toutes les réponses ne font que réitérer une variation du code que vous avez déjà, et aucune d'entre elles ne répond à la question à mon avis. Votre code semble correct, AFAICT. Très probablement, vous manquez juste android.permission.VIBRATEdans AndroidManifest.xml.
Olaf Dietsche

À qui cela peut appliquer des solutions dans ce fil et qui n'a toujours pas de vibration sur les notifications, vous devrez peut-être d'abord activer la vibration de votre canal de notification. Jetez un œil à ceci: stackoverflow.com/a/47646166/8551764
Mostafa Arian Nejad

Réponses:


203

Certains codes factices peuvent vous aider.

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

Ajouter ci-dessous l'autorisation pour Vibration dans le AndroidManifest.xmlfichier

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

114
La vibratefonctionnalité +1 nécessite une <uses-permission android:name="android.permission.VIBRATE" />autorisation
ashakirov

1
Dans certains cas, vous devriez utiliser le format argb couleur hexadécimal, comme 0xffffffff, au lieu de Color.White, car il y a une petite chance que la machine utilisateur utilise Color (RVB) pour un paramètre ARVB et vous obtiendrez la mauvaise couleur. Cela m'est arrivé.
Beto Caldas

55
La vibration a maintenant un retard de 1000 ms. Si vous définissez le premier sur 0, il s'éteindra instantanément. C'est un schéma {retarder, vibrer, dormir, vibrer, dormir}.
Tom

11
Je n'ai pas eu besoin d'ajouter <uses-permission android:name="android.permission.VIBRATE" />au travail.
Iqbal

1
Quelqu'un sait comment utiliser setSound sur l'API 26?
Rodrigo Manguinho

61

Une extension de la réponse de TeeTracker,

pour obtenir le son de notification par défaut, vous pouvez procéder comme suit

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

Cela vous donnera le son de notification par défaut.


35

Notification Vibrer

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

Du son

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

pour plus d'option sonore


2
Pour le vibreur, assurez-vous d'inclure le <uses-permission android:name="android.permission.VIBRATE" />dans votre AndroidManifest.xml
Aaron Esau

Combien de temps dure ce vibreur? ou va-t-il juste vibrer une fois?
Zapnologica

13

Cela fonctionne bien pour moi, vous pouvez l'essayer.

 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

Il s'agit d'un moyen simple d'appeler une notification en utilisant le vibreur et le son par défaut du système.

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

Ajoutez une autorisation de vibration si vous comptez l'utiliser:

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

Bonne chance,'.


Quelqu'un peut-il me dire pourquoi les vibrations ne fonctionnent pas lorsque le téléphone est en cours d'appel? OU pouvons-nous faire une notification pour forcer la vibration même si le téléphone est en appel

Cela m'a aidé notificationBuilder.setDefaults (notification.defaults);
Saveen

@ user526206, je ne sais pas. Je n'ai jamais testé ça. Vous pouvez ouvrir une nouvelle question car cela n'a rien avec le comportement de notification.
Maher Abuthraa

7

J'utilise le code suivant et cela fonctionne très bien pour moi.

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

Pour Kotlin, vous pouvez essayer ceci.

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

1

// définir l'audio de notification

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

1

Pour prendre en charge la version SDK> = 26, vous devez également créer NotificationChanel et y définir un modèle de vibration et un son. Il existe un exemple de code 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)
    }

Et voici le constructeur:

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

Assurez-vous que vous AudioAttributesêtes bien choisi pour en savoir plus ici .

En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.