Vibrate and Sound defaults on notification

后端 未结 9 1159
天涯浪人
天涯浪人 2020-12-04 07:37

I\'m trying to get a default vibrate and sound alert when my notification comes in, but so far no luck. I imagine it\'s something to do with the way I set the defaults, but

9条回答
  •  执念已碎
    2020-12-04 08:23

    This is a simple way to call notification by using default vibrate and sound from system.

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

    Add vibrate permission if you are going to use it:

    
    

    Good luck,'.

提交回复
热议问题