previous Media Track - Android Media

Android examples for Media:Audio

Description

previous Media Track

Demo Code


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

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

public class Main {
    public static void previousTrack() {
        //        sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS, context);
        dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_MEDIA_PREVIOUS));
        dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_MEDIA_PREVIOUS));
    }// w  w w. jav a 2 s  .c  o m

    /**
     * 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