简体   繁体   中英

Android using intents to control media player?

I want to send a broadcast (or is it an intent?) from my app that will go to the next track of a music player if something is playing, or play/pause, etc. Here is the code that I have so far:

    final Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.putExtra(Intent.EXTRA_KEY_EVENT, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
    context.sendBroadcast(i); 

However as far as I can tell from my testing this code snippet doesn't quite do anything. Btw I put this code into a function and call it from a background service, in case that's relevant.

So how can I get this functionality working? If it's not possible for some reason I'm open to suggestions for work-arounds and/or alternate solutions.

Much appreciated, thanks.

You're using EXTRA_KEY_EVENT improperly. See Intent#EXTRA_KEY_EVENT . You need to instantiate a new KeyEvent object with the KEYCODE_MEDIA_PLAY_PAUSE keycode. Just passing the keycode in the intent is passing it as an Integer, not as a KeyEvent .

This thread shows an example of creating the KeyEvent object.

Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT,new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
sendOrderedBroadcast(i, null);

i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT,new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT));
sendOrderedBroadcast(i, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM