Android开启关闭手机扬声器

 /**
     * 当前音量
     */
    private static int currVolume = 0;
    private AudioManager audioManager;
@Override
public void openSpeaker() {
    try {
        if (audioManager == null) {
            audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
        }
        // 获取当前通话音量
        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();
    }
    ToastUtil.showToast( "打开扬声器");
}
    @Override
    public void closeSpeaker() {
        try {
            if (audioManager == null) {
                audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
            }
            if (audioManager.isSpeakerphoneOn()) {
                audioManager.setSpeakerphoneOn(false);
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume,AudioManager.STREAM_VOICE_CALL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ToastUtil.showToast( "关闭扬声器");
    }

你可能感兴趣的:(Android)