Rung và Âm thanh mặc định trên thông báo


93

Tôi đang cố gắng nhận cảnh báo bằng âm thanh và rung mặc định khi thông báo của tôi đến nhưng vẫn chưa thành công. Tôi tưởng tượng đó là điều gì đó liên quan đến cách tôi đặt giá trị mặc định, nhưng tôi không chắc về cách sửa nó. Có suy nghĩ gì không?

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ất cả các câu trả lời chỉ nhắc lại một số biến thể của mã bạn đã có và không có câu trả lời nào trong số đó trả lời câu hỏi theo ý kiến ​​của tôi. Mã của bạn trông ổn, AFAICT. Rất có thể, bạn chỉ bị thiếu android.permission.VIBRATEtrong AndroidManifest.xml.
Olaf Dietsche

Người có thể áp dụng các giải pháp trong chủ đề này và vẫn không có bất kỳ rung động nào trên thông báo, trước tiên bạn có thể cần bật chế độ rung cho kênh thông báo của mình. Hãy xem cái này: stackoverflow.com/a/47646166/8551764
Mostafa Arian Nejad

Câu trả lời:


203

Một số mã giả có thể giúp bạn.

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

Thêm quyền bên dưới cho Rung trong AndroidManifest.xmltệp

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

114
1 vibratetính năng đòi hỏi <uses-permission android:name="android.permission.VIBRATE" />sự cho phép
ashakirov

1
Trong một số trường hợp, bạn nên sử dụng định dạng argb màu hex, như 0xffffffff, thay vì Color.White, bởi vì có một phần nhỏ khả năng thiết bị người dùng sử dụng Màu (RGB) cho thông số ARGB và bạn sẽ nhận được màu sai. Điều này đã xảy ra với tôi.
Beto Caldas

55
Rung bây giờ có độ trễ là 1000 ms. Nếu bạn đặt giá trị đầu tiên thành 0, nó sẽ tắt ngay lập tức. Đó là một mẫu {trễ, rung, ngủ, rung, ngủ}.
Tom,

11
Tôi không cần phải thêm <uses-permission android:name="android.permission.VIBRATE" />vào công việc.
Iqbal

1
Có ai biết cách sử dụng setSound trên API 26 không?
Rodrigo Manguinho

61

Phần mở rộng cho câu trả lời của TeeTracker,

để có âm thanh thông báo mặc định, bạn có thể làm như sau

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

Điều này sẽ cung cấp cho bạn âm thanh thông báo mặc định.


35

Rung thông báo

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

Âm thanh

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

để có thêm tùy chọn âm thanh


2
Đối với một rung, hãy chắc chắn bao gồm <uses-permission android:name="android.permission.VIBRATE" />trong AndroidManifest.xml của bạn
Aaron Ê-sau

rung động này kéo dài bao lâu? hay nó sẽ chỉ rung một lần?
Zapnologica

13

Nó làm việc tốt cho tôi, bạn có thể thử nó.

 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

Đây là một cách đơn giản để thông báo cuộc gọi bằng cách sử dụng chế độ rung và âm thanh mặc định từ hệ thống.

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

Thêm quyền rung nếu bạn định sử dụng:

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

Chúc may mắn,'.


Ai đó có thể cho tôi biết tại sao rung không hoạt động khi điện thoại đang gọi không? Ta có thể thực hiện thông báo cho lực lượng rung ngay cả trong điện thoại tham gia cuộc gọi

Nó đã giúp tôi notificationBuilder.setDefaults (notification.defaults);
Saveen

@ user526206, tôi không biết. Tôi chưa bao giờ thử nghiệm điều đó. Bạn có thể mở câu hỏi mới vì điều này không liên quan gì đến hành vi thông báo.
Maher Abuthraa

7

Tôi đang sử dụng mã followung và nó hoạt động tốt đối với tôi.

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

Đối với Kotlin, bạn có thể Thử điều này.

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

1

// đặt âm thanh thông báo

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

1

Để hỗ trợ phiên bản SDK> = 26, bạn cũng nên tạo NotificationChanel và đặt kiểu rung và âm thanh ở đó. Có một mẫu mã 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)
    }

Và đây là trình xây dựng:

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

Hãy chắc chắn rằng bạn AudioAttributesđược chọn đúng để đọc thêm ở đây .

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.