[英]How to turn off all sounds and vibration via Android API
我正在构建一个 Android 应用程序,并且我正在尝试在应用程序启动时禁用设备的所有声音和振动。
我是新手,所以我找不到如何做到这一点。
任何想法?
提前致谢。
谢谢::)我自己回复以完成答案:
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setRingerMode(aManager.RINGER_MODE_SILENT);
在此处检查并查看带有RINGER_MODE_SILENT
选项的public void setRingerMode (int ringerMode)
。
您需要首先在清单文件中添加更改音频设置的权限。 为了能够将振铃模式设置为静音,您必须请求访问通知策略的权限
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
然后在onClick
事件中(下面是textView
)您可以一一切换声音设置:
// attach an OnClickListener
audioToggle.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// your click actions go here
NotificationManager notificationManager = (NotificationManager) getActivity().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
return;
}
ToggleDoNotDisturb(notificationManager);
}
});
private void ToggleDoNotDisturb(NotificationManager notificationManager) {
if (notificationManager.getCurrentInterruptionFilter() == NotificationManager.INTERRUPTION_FILTER_ALL) {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
audioToggle.setText(R.string.fa_volume_mute);
} else {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
audioToggle.setText(R.string.fa_volume_up);
}
}
您还需要检查权限
NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.