简体   繁体   中英

How to turn off vibration of Notifications in android

I'm developing an app that handles sound and vibration of apps' notifications . I am listening to notifications using NotificationListenerService . I am able to turn on or off notification's sound using AudioManager as follows:

// It turns off notification's sound
myAudioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true); 

// It turns on notification's sound
myAudioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, false); 

I have also tried to turn on or off notification's vibration with following code but it didn't work on my phone which has Android KitKat 4.4.4

// to turn off notification's vibration
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);

// to turn on notification's vibration
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);

Here's what I did. In my NotificationListenerService, I cancel the original notification, turn off its vibration, and send it out again. Code like this should work:

Integer key = 1;

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Notification n = sbn.getNotification();
    if (doINeedToDisableVibration(sbn)) {
        cancelNotification(sbn.getKey());
        n.defaults &= ~Notification.DEFAULT_VIBRATE;
        n.vibrate = null;
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            synchronized(key) {
                nm.notify(key++, n);
            }
    }
}

In doINeedToDisableVibration(sbn), either make sure that vibration is on in the notification, or else check that sbn.packageName is NOT the same as your own package name, or you have a danger of generating an endless loop.

I am not sure this will work with all notifications. But it did work with MMS notifications on my HTC One A9 with 6.0.

setVibrateSetting api is deprecated in API 16. As per android developer site,

Applications should maintain their own vibrate policy based on current ringer mode that can be queried via getRingerMode().

So, you try with Ringer mode to enable/disable vibration.

 AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

for setting silent mode :

audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

For normal mode :

audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

For ring vibrate mode:

audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM