当前位置: 代码迷 >> Android >> [AndroidTips]打开/封锁免提(SpeakerPhone)
  详细解决方案

[AndroidTips]打开/封锁免提(SpeakerPhone)

热度:402   发布时间:2016-05-01 20:06:34.0
[AndroidTips]打开/关闭免提(SpeakerPhone)

//打开扬声器
???? public void OpenSpeaker() {

???????? try{
???????? AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
???????? audioManager.setMode(AudioManager.ROUTE_SPEAKER);
???????? currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

???????? if(!audioManager.isSpeakerphoneOn()) {
?????????? 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) mContext.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();
??????? }
????????? //Toast.makeText(context,"揚聲器已經關閉",Toast.LENGTH_SHORT).show();
??? }

?

?

setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL. Try this:

AudioManager audioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(true);

Please remember set back to normal mode before you quit.

?

Your code needs to have android.permission.MODIFY_AUDIO_SETTINGS permission set in your manifest file because setSpeakerPhoneOn() requires that permission.