play Pause Track - Android android.os

Android examples for android.os:IBinder

Description

play Pause Track

Demo Code

import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.KeyEvent;
import java.io.IOException;

public class Main{

    public static void playPauseTrack() {
        dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
        dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    }/*w  w  w.  ja v a  2s  .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) {


        try {

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

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

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

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

}

Related Tutorials