android 打开 关闭 免提

要操作手机的audio,需要加入以下权限,否则无法正常开启关闭免提:


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


下面是项目中使用的打开和关闭免提的代码:

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


Context ctx = AppClass.getInstance();

try {
AudioManager audioManager = (AudioManager) ctx
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.ROUTE_SPEAKER);

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 static void CloseSpeaker() {


Context ctx = AppClass.getInstance();


try {
AudioManager audioManager = (AudioManager) ctx
.getSystemService(Context.AUDIO_SERVICE);


int currVolume = audioManager
.getStreamVolume(AudioManager.STREAM_VOICE_CALL);


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 打开 关闭 免提)