Bildirimde Titreşim ve Ses varsayılanları


94

Bildirimim geldiğinde varsayılan bir titreşim ve sesli uyarı almaya çalışıyorum, ancak şu ana kadar şans yok. Varsayılanları belirleme şeklimle ilgili bir şey olduğunu hayal ediyorum, ancak bunu nasıl düzelteceğimden emin değilim. Düşüncesi olan var mı?

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
Tüm yanıtlar yalnızca sahip olduğunuz kodun bazı varyasyonlarını yineliyor ve bence hiçbiri soruyu yanıtlamıyor. Kodunuz iyi görünüyor, AFAICT. Büyük olasılıkla, android.permission.VIBRATEAndroidManifest.xml'de eksiksiniz.
Olaf Dietsche

Bu ileti dizisindeki çözümleri uygulayabilecek ve hala bildirimlerde titreşim olmayanlara, önce bildirim kanalınızın titreşimini etkinleştirmeniz gerekebilir. Şuna bir göz atın: stackoverflow.com/a/47646166/8551764
Mostafa Arian Nejad

Yanıtlar:


205

Bazı sahte kodlar size yardımcı olabilir.

   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.xmlDosyadaki Titreşim için aşağıdaki izni ekleyin

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

115
+1 vibrateözelliği için <uses-permission android:name="android.permission.VIBRATE" />izin gerekiyor
ashakirov

1
Bazı durumlarda Color.White yerine 0xffffffff gibi hex color argb formatını kullanmanız gerekir, çünkü kullanıcı cihazının ARGB parametresi için Color (RGB) kullanması için küçük bir şans vardır ve yanlış rengi alırsınız. Bu benimle oldu.
Beto Caldas

55
Titreşim artık 1000 ms'lik bir gecikmeye sahip. İlkini 0 olarak ayarlarsanız, anında kapanacaktır. Bu bir {gecikme, titreşim, uyku, titreşim, uyku} modelidir.
Tom

11
<uses-permission android:name="android.permission.VIBRATE" />İşe eklemem gerekmedi .
Iqbal

1
API 26'da setSound'un nasıl kullanılacağını bilen var mı?
Rodrigo Manguinho

61

TeeTracker'ın cevabının bir uzantısı,

varsayılan bildirim sesini almak için aşağıdaki işlemleri yapabilirsiniz

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

Bu size varsayılan bildirim sesini verecektir.


36

Bildirim Titreşimi

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

Ses

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

daha fazla ses seçeneği için


2
Titreşimli olan <uses-permission android:name="android.permission.VIBRATE" />için, AndroidManifest.xml
Aaron Esau

bu titreşim ne kadar sürer? yoksa sadece bir kez mi titreşecek?
Zapnologica

13

Benim için iyi çalışıyor, deneyebilirsin.

 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

Bu, sistemden varsayılan titreşim ve sesi kullanarak bildirim aramak için basit bir yoldur.

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

Kullanacaksanız titreşim izni ekleyin:

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

İyi şanslar,'.


Biri bana telefon görüşmesi sırasında titreşimin neden çalışmadığını söyleyebilir mi? VEYA telefon görüşme sırasında bile titreşimi zorlamak için bildirim yapabilir miyiz

BildirimBuilder.setDefaults (notification.defaults) bana yardımcı oldu;
2017

@ user526206, bilmiyorum. Bunu hiç test etmedim. Bildirim davranışıyla ilgili hiçbir şey olmadığı için yeni soru açabilirsiniz.
Maher Abuthraa

7

Aşağıdaki kodu kullanıyorum ve benim için iyi çalışıyor.

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

2

// bildirim sesini ayarla

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

1

Kotlin için bunu deneyebilirsiniz.

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

1

SDK sürümü> = 26'yı desteklemek için ayrıca NotificationChanel oluşturmalı ve orada bir titreşim modeli ve ses ayarlamalısınız. Bir Kotlin kod örneği var:

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

Ve bu kurucu:

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

BuradaAudioAttributes daha fazlasını okumak için doğru seçtiğinizden emin olun .

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.