转载地址:http://blog.sina.com.cn/s/blog_5da93c8f0101g447.html
Q:如何设置android的扬声器的开启状态?
A:
只能在MODE_IN_CALL模式下设置Speakerphone(扩音器)的开启状态
步骤1:
AndroidMainfest.xml中添加权限:android.permission.MODIFY_AUDIO_SETTINGS
步骤2:
设置扬声器开启或关闭
AudioManager audioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
检测扬声器是否开启
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
boolean isSpeakphoneOn = audioManager.isSpeakerphoneOn();
注意当不需要时一定要将音频模式设置回MODE_NORMAL(普通状态)
AudioManager audioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_NORMAL);
//打开扬声器
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();
}