我希望在设备插入音频插孔时(不仅限于耳机),可以播放音频文件,与Android 4.3及以上版本有关,如有必要,我愿意获取root权限。
以下是我目前尝试过的方法:
以下是我目前尝试过的方法:
Some kind of hack but it is not working.
try { Class audioSystemClass = Class.forName("android.media.AudioSystem"); Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class); setForceUse.invoke(null, 1, 1); MediaPlayer mp = MediaPlayer.create(this, R.raw.bad); mp.start(); } catch (ClassNotFoundException e) { Log.d("mediaException", "class", e); } catch (NoSuchMethodException e) { Log.d("mediaException", "method", e); } catch (IllegalAccessException e) { Log.d("mediaException", "access", e); } catch (InvocationTargetException e) { Log.d("mediaException", "invocation", e); }
Found this here in some thread but it is also not working:
AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_NORMAL); audioManager.setSpeakerphoneOn(true); MediaPlayer mp = MediaPlayer.create(this, R.raw.bad); mp.start();
Using MediaRouter class I tried to get available routes. But when something is plugged in audio jack only route available is "Headphones".
MediaRouter router = (MediaRouter) this.getSystemService(Context.MEDIA_ROUTER_SERVICE); for (int i = 0; i < router.getRouteCount(); i++) { Log.d("playSound", router.getRouteAt(i).toString()); }