Android 中如何监听耳机键消息

在研究一个功能:Android如何通过耳机键来拍照/摄像,好处自不用多说了,拍照时可以防抖

那么这引出一个问题,如何在 Camera/VideoCamera Activity中监听耳机键。

耳机键在 android 中的定义为

/** Key code constant: Headset Hook key.
* Used to hang up calls and stop media. */
public static final int KEYCODE_HEADSETHOOK    = 79;

主要用来接听/挂断 电话,播放/暂停音乐视频等

监听耳机键有两种方式:

1,直接在 Activity 的 onKeyDown 或 onKeyUp 函数中添加对应的 case 即可

@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
  ……
  case KeyEvent.KEYCODE_HEADSETHOOK:
   //add your code here
   ……
   
        }
        return super.onKeyUp(keyCode, event);
    }

2,注册 BroadcastReceiver 来响应该按键


 
 //  listener media button
 private BroadcastReceiver mMediaButtonReceiver = null;
 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
    @Override
  public void onReceive(Context context, Intent intent) {
   Log.v(TAG," call MediaButtonBroadcastReceiver");
    KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    Log.v(TAG, " event "+event);
    if ((event != null)&& (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
    Toast.makeText(VideoCamera.this, R.string.hook, Toast.LENGTH_SHORT).show();
    }
  }
  }
 
  //registerReceiver
  IntentFilter mediaButtonIntentFilter = new IntentFilter();
  mediaButtonIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
  mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
  registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
 
  //unregisterReceiver
  if (mMediaButtonReceiver != null){
   unregisterReceiver(mMediaButtonReceiver);
   mMediaButtonReceiver = null;
  }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ff56ed89bccd979a5a9e54f5f9072cf2.html