如何通过Android API关闭所有声音和振动

时间:2011-05-01 11:46:19

标签: android

我正在构建一个Android应用程序,我正在尝试在应用程序启动时禁用设备的所有声音和振动。

我是新手,我找不到怎么做。

有什么想法吗?

提前致谢,

3 个答案:

答案 0 :(得分:13)

谢谢! :)我回复自己完成答案:

AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setRingerMode(aManager.RINGER_MODE_SILENT);

答案 1 :(得分:4)

点击此处this,然后使用public void setRingerMode (int ringerMode)选项查看RINGER_MODE_SILENT

答案 2 :(得分:0)

您需要先添加到清单文件,然后才能更改音频设置。为了能够将铃声模式设置为静音,您必须请求访问通知策略的权限

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