How to turn off vibration of Notifications in android

筅森魡賤 提交于 2019-12-23 04:14:17

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/35765481/how-to-turn-off-vibration-of-notifications-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!