簡體   English   中英

如何通過 Android API 關閉所有聲音和振動

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM