Sends a media button event. - Android android.provider

Android examples for android.provider:MediaStore

Description

Sends a media button event.

Demo Code


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

import android.view.KeyEvent;
import java.io.IOException;

public class Main {
    /**//from   w ww.ja v  a 2  s.  c  o m
     * Sends a media button event.
     * Does not work with all audio players (e.g. Spotify).
     * @param keycode
     * @param context
     */
    public static void sendMediaButtonEvent(int keycode, Context context) {

        try {
            Process process = Runtime.getRuntime().exec(
                    "input keyevent " + keycode);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
                KeyEvent.ACTION_DOWN, keycode));
        context.sendOrderedBroadcast(intent, null);

        //        intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
                KeyEvent.ACTION_UP, keycode));
        context.sendOrderedBroadcast(intent, null);
    }
}

Related Tutorials