实现方式一:只能在程序为前台时监控
在Activity中即可监听
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.i("MainActivity-onKeyUp", "" + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_HEADSETHOOK:
Toast.makeText(MainActivity.this, "Pause_Up", Toast.LENGTH_SHORT).show();
return false;
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.i("MainActivity-onKeyDown", "" + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_HEADSETHOOK:
Toast.makeText(MainActivity.this, "Pause_Down", Toast.LENGTH_SHORT).show();
return false;
}
return super.onKeyUp(keyCode, event);
}
实现方式二:前后台均可
1.自定义Receiver
public class EarphoneReceiver extends BroadcastReceiver {
public EarphoneReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event.getAction() == KeyEvent.ACTION_UP) {
//// TODO: 2016/2/18 0018 按下时操作
Message msg = Message.obtain();
msg.what = 100;
handler.sendMessage(msg);
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 100:
//// TODO: 2016/2/18 0018 操作
EarphoneButtonHelper.EarphoneListener listener = EarphoneButtonHelper.getInstance().getListener();
if (listener != null) {
listener.onClick();
}
break;
}
}
};
}
AndroidManifast.xml中注册
<receiver android:name=".EarphoneReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
2.注册/取消Receiver
/**
* 取消广播接收器
* @param context
*/
public void unrigisterReceiver(Context context) {
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
ComponentName name = new ComponentName(context.getPackageName(), EarphoneReceiver.class.getName());
mAudioManager.unregisterMediaButtonEventReceiver(name);
}
/**
* 注册广播接收器
* @param context
*/
public void registerReceiver(Context context) {
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
ComponentName name = new ComponentName(context.getPackageName(), EarphoneReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(name);
}