简体   繁体   English

Android 使用意图控制媒体播放器?

[英]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:我想从我的应用程序发送一个广播(或者它是一个意图?),如果正在播放或播放/暂停等,它将 go 到音乐播放器的下一首曲目。这是我到目前为止的代码:

    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.顺便说一句,我将此代码放入 function 并从后台服务调用它,以防万一。

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.您使用EXTRA_KEY_EVENT不当。 See Intent#EXTRA_KEY_EVENT .请参阅Intent#EXTRA_KEY_EVENT You need to instantiate a new KeyEvent object with the KEYCODE_MEDIA_PLAY_PAUSE keycode.您需要使用 KEYCODE_MEDIA_PLAY_PAUSE 键码实例化一个新的KeyEvent KEYCODE_MEDIA_PLAY_PAUSE Just passing the keycode in the intent is passing it as an Integer, not as a KeyEvent .仅在意图中传递键码就是将其作为 Integer 传递,而不是作为KeyEvent传递。

This thread shows an example of creating the KeyEvent object. 此线程显示了创建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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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