Dispatches a media key event. - Android android.provider

Android examples for android.provider:MediaStore

Description

Dispatches a media key event.

Demo Code


//package com.java2s;
import android.content.Context;

import android.os.IBinder;
import android.view.KeyEvent;

public class Main {
    /**/*from ww  w .ja  v  a2  s .com*/
     * Dispatches a media key event.
     * Uses reflection to leverage the mechanism the lock screen media widget is using (making it work with Spotify).
     *
     * Credits to http://stackoverflow.com/questions/12573442/is-google-play-music-hogging-all-action-media-button-intents
     *
     * @param keyEvent the KeyEvent to be dispatched
     */
    public static void dispatchMediaKeyEvent(KeyEvent keyEvent) {

        /*
         * Attempt to execute the following with reflection.
         *
         * [Code]
         * IAudioService audioService = IAudioService.Stub.asInterface(b);
         * audioService.dispatchMediaKeyEvent(keyEvent);
         */
        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);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials