在我的应用程序中,有一个读卡器使用设备的音频插孔。现在,我的问题是当读卡器在设备的耳机插孔中完好无损时,我想从内置扬声器发出声音。
以下是我尝试过的代码:
1)使用反射方法
Class audioSystemClass;
try {
audioSystemClass = Class
.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod(
"setForceUse", int.class, int.class);
// First 1 == FOR_MEDIA, second 1 == FORCE_SPEAKER. To go
// back to the default
// behavior, use FORCE_NONE (0).
setForceUse.invoke(null, 1, 1);
final float maxVolume = mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);
} catch (ClassNotFoundException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (NoSuchMethodException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e("Test", e.toString());
e.printStackTrace();
}
2) 使用 setMode 方法
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
mAudioManager.setSpeakerphoneOn(true);
float maxVolume = mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_RING);
soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);
但是这两个代码仅在那些具有默认 FM 应用程序的设备中运行。但我想在所有设备中都有这个功能。
请分享你的经验!!