开发者

How to turn off all sounds and vibration via Android API

I'm building an Android app, and I'm trying to disable all sounds and vibration of the device开发者_如何学C when the app starts.

I'm a newbie so I cannot find how to do that.

Any idea?

Thanks in advance.


Thanks! :) I reply myself to complete the answer:

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


Check this here and take a look at public void setRingerMode (int ringerMode) with the RINGER_MODE_SILENT option.


You need to first add to the manifest file, permission to change the audio settings. To be able to set ringer mode to silent, you must ask permission to access notification policy

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

and then in a onClick event (below is for a textView) you can toggle the sound settings one by one:

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

also you need to check permissions

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜