java.lang.NoSuchMethodException: dispatchMediaKeyEvent [class android.view.KeyEvent]

java.lang.NoSuchMethodException: dispatchMediaKeyEvent [class android.view.KeyEvent]

我正在尝试使用媒体事件来播放、暂停、下一首、上一首来自我的 android 应用程序的音乐。

当我在 Samsung s4(Android 版本 4.4.2)上 运行 它时,我可以执行所有操作。但是我无法从我的 Nexus 5(Android 版本 5.0.1)执行这些操作。

我在处理按键事件时出错。

我的代码是:

private void handleMediaKeyEvent(KeyEvent keyEvent) {

    /*
     * Attempt to execute the following with reflection. 
     * 
     * [Code]
     * IAudioService audioService = IAudioService.Stub.asInterface(b);
     * audioService.dispatchMediaKeyEvent(keyEvent);
     */
    boolean dispatchMediaKeyEvent = false;
    try {

        // Get binder from ServiceManager.checkService(String)
        IBinder iBinder  = (IBinder) Class.forName("android.os.ServiceManager")
        .getDeclaredMethod("checkService",String.class)
        .invoke(null, Context.AUDIO_SERVICE);

        // get audioService from IAudioService.Stub.asInterface(IBinder)
        Object audioService  = Class.forName("android.media.IAudioService$Stub")
                .getDeclaredMethod("asInterface",IBinder.class)
                .invoke(null,iBinder);

        // Dispatch keyEvent using IAudioService.dispatchMediaKeyEvent(KeyEvent)
        Class.forName("android.media.IAudioService")
        .getDeclaredMethod("dispatchMediaKeyEvent",KeyEvent.class)
        .invoke(audioService, keyEvent);            

        dispatchMediaKeyEvent = true;
    }  catch (Exception e1) {
        e1.printStackTrace();
    }
    // If dispatchMediaKeyEvent failed then try using broadcast
    if (!dispatchMediaKeyEvent) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        mContext.sendOrderedBroadcast(intent, null);
    }
}

我得到错误:

02-14 15:37:08.744: W/System.err(3474): java.lang.NoSuchMethodException: dispatchMediaKeyEvent [class android.view.KeyEvent]
02-14 15:37:08.745: W/System.err(3474):     at java.lang.Class.getMethod(Class.java:664)
02-14 15:37:08.745: W/System.err(3474):     at java.lang.Class.getDeclaredMethod(Class.java:626)

任何人都可以提出在所有 android 设备上实现 运行 的解决方案吗?

dispatchMediaKeyEvent继承自AudioManagerclass。 您将其引用为 boolean.

http://developer.android.com/reference/android/media/AudioManager.html#dispatchMediaKeyEvent(android.view.KeyEvent)

这是使用此事件的代码的样子

AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

long eventtime = SystemClock.uptimeMillis() - 1;
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0);
am.dispatchMediaKeyEvent(downEvent);