歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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;
  }

Copyright © Linux教程網 All Rights Reserved