首先注册一个receiver, 使用的IntentFilter包含Intent.ACTION_HEADSET_PLUG, 这样在receiver的onReceive函数里就可以监测到耳机拔出和插入的事件了。
例如下面的代码:
if(action.equals(Intent.ACTION_HEADSET_PLUG)){
//headphone plugged
if(intent.getIntExtra("state", 0) == 1){
//do something
//headphone unplugged
}else{
//do something
}
}
那怎么监测耳机按钮的事件呢?
只需要在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
}
PS:转自http://site.douban.com/widget/notes/110027/note/120650125/