静音按钮不起作用

时间:2018-02-14 11:27:50

标签: java android

您好我正在尝试为我的Android项目应用添加一个静音按钮,只是在这里学习基础知识。我创建了一个Button(这是将来我将尝试使用Switch)id设置为android:id="@+id/muteBtn"并在java Button muteBtn = (Button) findViewById(R.id.muteBtn) ;中声明了变量 当它点击它必须将模式置于静音模式时我添加了user-permission,因为它给了我一个错误Not allowed to change Do Not Disturb state

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

这里是按钮点击监听器

 muteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                    && !notificationManager.isNotificationPolicyAccessGranted()) {

                Intent intent = new Intent(
                        android.provider.Settings
                                .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

                startActivity(intent);
            }
            else {
                AudioManager audioManager = (AudioManager) Settings.this.getSystemService(Context.AUDIO_SERVICE);
                audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            }
        }
    });

这种方法没有任何建议吗?

更新1

我刚才注意到这段代码有效但ringer音量下降而不是media

2 个答案:

答案 0 :(得分:0)

public void onClick(查看v){

  switch (v.getId()) {
  case R.id.wmute:
    AudioManager.setMode(AudioManager.MODE_IN_CALL);
    AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
     break;
  default:
     break;
  }

}           }

   }

答案 1 :(得分:0)

试试这个:我假设你想放下音乐音量而不是把手机放在静音模式......如果我错了请纠正我..

    if (!isMute) {
        AudioManager mAudioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        isMute = true;
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
        imageButtonMute.setImageDrawable(getResources().getDrawable(R.mipmap.mute_off));
     } else {

 imageButtonMute.setImageDrawable(getResources().getDrawable(R.mipmap.mute));
      AudioManager mAudioManager = (AudioManager) 
      activity.getSystemService(Context.AUDIO_SERVICE);
     isMute = false;                       
     mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
    }