开发者

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 int开发者_运维知识库o 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜