Detect presses to headset buttons on Android?

前端 未结 3 1326
梦谈多话
梦谈多话 2021-02-02 17:04

How can I detect if a buton, on a pair of headphones, was pressed while running an Android app? Music applications use to this button to stop, play, pause music, etc.

D

相关标签:
3条回答
  • 2021-02-02 17:56

    Use the ACTION_MEDIA_BUTTON and ACTION_AUDIO_BECOMING_NOISY. Refer this doc: Developer Android

    0 讨论(0)
  • 2021-02-02 17:57

    It's the ACTION_MEDIA_BUTTON intent.

    0 讨论(0)
  • 2021-02-02 18:07

    There's a simpler way which doesn't require any BroadcastReceiver to be registered if you only want to listen for headset button callbacks while your app (particular activity) is running, simply override Activity onKeyDown method:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_HEADSETHOOK){
            //handle click
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
提交回复
热议问题