import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import java.lang.reflect.Method;
public class AudioUtils {
private AudioUtils() {
}
/**
* 设置扬声器启用状态,true为启用,兼容5.0及其以上版本
* @param context 5.0以下可以传递ApplicationContext,否则请传递Activity
* @param on 扬声器启用状态,true为启用
*/
public static void setSpeakerphoneOn(Context context, boolean on) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
audioManager.setMode(on ? AudioManager.MODE_NORMAL : AudioManager.MODE_IN_CALL);
} else {
try {
Activity activity= (Activity) context;
activity.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
if (on) {
audioManager.setMicrophoneMute(false);
audioManager.setSpeakerphoneOn(true);
audioManager.setMode(AudioManager.MODE_NORMAL);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(AudioManager.MODE_NORMAL);
setForceUse.invoke(null, 0, 0);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
AudioUtils
最新推荐文章于 2024-08-19 15:19:12 发布