Android开发之关闭和打开Speaker(扬声器)的方法

时间:2021-09-09 14:43:08

本文实例讲述了Android开发之关闭和打开Speaker(扬声器)的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private int currVolume = 0;
/**
* 打开扬声器
*/
private void openSpeaker() {
    try{
      AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      audioManager.setMode(AudioManager.ROUTE_SPEAKER);
      currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
      if(!audioManager.isSpeakerphoneOn()) {
        //setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL.
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        audioManager.setSpeakerphoneOn(true);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
            audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL ),
            AudioManager.STREAM_VOICE_CALL);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
}
/**
* 关闭扬声器
*/
public void closeSpeaker() {
    try {
      AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      if(audioManager != null) {
        if(audioManager.isSpeakerphoneOn()) {
          audioManager.setSpeakerphoneOn(false);
          audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,currVolume,
              AudioManager.STREAM_VOICE_CALL);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
}

希望本文所述对大家Android程序设计有所帮助。