android+耳机插拔和耳机按键检测

1.耳机插拔

首先,在oncreate里面注册receiver,

 registerReceiver(headSetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG)); 


接着,是接收广播部分:

  private final BroadcastReceiver headSetReceiver = new BroadcastReceiver() {
        @Override
         public void onReceive(Context context, Intent intent) {
            
            Log.d(TAG,"into headsetreceiver!");
               String action = intent.getAction();
               
               
               if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
                //headphone plugged
                   if(intent.getIntExtra("state", 0) == 1){
                       //do something
                    Log.d(TAG,"this is headphone plugged");
                    headsetState.setText("耳机检测:插入");
                   
                    
                   //headphone unplugged
                   }else{
                       //do something
                    Log.d(TAG,"this is headphone unplugged");
                    headsetState.setText("耳机检测:没有插入");
                   }
               }
         }
 };


 

2.耳机按键检测

/*检测耳机按键*/
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HEADSETHOOK:
			 //DisplayToast("按下:耳机键");
			 headsetState.setText("耳机检测:插入,耳机按键按下");
			break;
		}
		return true;
	}
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HEADSETHOOK:
			 //DisplayToast("弹起:耳机键");
			 headsetState.setText("耳机检测:插入,耳机按键弹起");
			break;
		}
		return true;
	}


 就可以检测到耳机按键了,网路上有人说可以通过下面的方法检测耳机按键,并且是转载了N多篇的。我试了  不行。。。  希望有成功的哥们,看到后给我留言讲讲,交流很重要。。。

只需要在filter里面加入Intent.ACTION_MEDIA_BUTTON


然后在onReceive函数里面处理


 final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN){
           //do something         
}  



上面提到的问题  ,现在明白了  是广播接收有一个优先级的概念在里面,而 hook 被系统的自带的播发器给截获了,用完以后又给销毁了  所以导致我的应用监听不到hook按键 ,只要提升广播接收的优先级即可   系统的是1000  我的是1000+1;  ok!

你可能感兴趣的:(android+耳机插拔和耳机按键检测)