在 Android 中接收耳机的操作

Receive the actions of a headset in Android

我正在尝试为 Android 编写一个音乐播放器作为学校的一个项目,我试图拦截我的蓝牙耳机(Parrot Zik 2.0,如果重要的话)的动作。

这是我当前的代码:

AndroidManifest.xml :

<receiver android:name=".core.MediaButtonReceiver">
    <intent-filter android:priority="100">
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

在我的 class MediaButtonReceiver 中,我出于测试目的写了以下内容 (Groovy) :

public class MediaButtonReceiver extends BroadcastReceiver
{

    @Override
    void onReceive(Context context, Intent intent)
    {
        def intentAction = intent.action
        if(!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) return

        def event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT) as KeyEvent
        if(event == null) return

        def action = event.action

        Log.e(this.class.toString(), "action : ${action}")
        switch(action)
        {
            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
                Log.e(this.class.toString(), "Play/pause")
                abortBroadcast()
                break
            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                Log.e(this.class.toString(), "Previous")
                abortBroadcast()
                break
            case KeyEvent.KEYCODE_MEDIA_NEXT:
                Log.e(this.class.toString(), "Next")
                abortBroadcast()
                break
            case KeyEvent.KEYCODE_VOLUME_UP:
                Log.e(this.class.toString(), "Volume up")
                abortBroadcast()
                break
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Log.e(this.class.toString(), "Volume down")
                abortBroadcast()
                break
        }
    }
}

当使用以下内容时:

E/class augier.fr.phoebius.core.MediaButtonReceiver﹕ 0
E/class augier.fr.phoebius.core.MediaButtonReceiver﹕ 1

所以看起来我确实捕捉到了一些东西,但看起来它只对应于按下然后释放按钮时的事件,我无法将其与任何特定动作相匹配。

我可能用错了,但到目前为止,我还没有找到解释如何在互联网上捕捉媒体相关事件的教程。

有什么想法吗?

而不是

def action = event.action

试试这个:

def action = event.keyCode