【记录】Android监听蓝牙耳机的按键事件

Android监听蓝牙耳机的按键事件

一、本文测试环境:

1、使用Dacom M10蓝牙耳机

2、成功监测到“电话键”(音量键没有监测到)

3、参考资料

4、参考源码

二、一些说明

【记录】Android监听蓝牙耳机的按键事件_第1张图片

连接蓝牙耳机后,需打开如图所示的两个选项。

二、代码实现

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		printToast(parseKeyCode(keyCode));
		return true;
	}

	public String parseKeyCode(int keyCode) {
		String ret = "";
		switch (keyCode) {
		case KeyEvent.KEYCODE_POWER:
			// 监控/拦截/屏蔽电源键 这里拦截不了
			ret = "get Key KEYCODE_POWER(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_RIGHT_BRACKET:
			// 监控/拦截/屏蔽返回键
			ret = "get Key KEYCODE_RIGHT_BRACKET";
			break;
		case KeyEvent.KEYCODE_MENU:
			// 监控/拦截菜单键
			ret = "get Key KEYCODE_MENU";
			break;
		case KeyEvent.KEYCODE_HOME:
			// 由于Home键为系统键,此处不能捕获
			ret = "get Key KEYCODE_HOME";
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			// 监控/拦截/屏蔽上方向键
			ret = "get Key KEYCODE_DPAD_UP";
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			// 监控/拦截/屏蔽左方向键
			ret = "get Key KEYCODE_DPAD_LEFT";
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			// 监控/拦截/屏蔽右方向键
			ret = "get Key KEYCODE_DPAD_RIGHT";
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			// 监控/拦截/屏蔽下方向键
			ret = "get Key KEYCODE_DPAD_DOWN";
			break;
		case KeyEvent.KEYCODE_DPAD_CENTER:
			// 监控/拦截/屏蔽中方向键
			ret = "get Key KEYCODE_DPAD_CENTER";
			break;
		case KeyEvent.FLAG_KEEP_TOUCH_MODE:
			// 监控/拦截/屏蔽长按
			ret = "get Key FLAG_KEEP_TOUCH_MODE";
			break;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			// 监控/拦截/屏蔽下方向键
			ret = "get Key KEYCODE_VOLUME_DOWN(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_VOLUME_UP:
			// 监控/拦截/屏蔽中方向键
			ret = "get Key KEYCODE_VOLUME_UP(KeyCode:" + keyCode + ")";
			break;
		case 220:
			// case KeyEvent.KEYCODE_BRIGHTNESS_DOWN:
			// 监控/拦截/屏蔽亮度减键
			ret = "get Key KEYCODE_BRIGHTNESS_DOWN(KeyCode:" + keyCode + ")";
			break;
		case 221:
			// case KeyEvent.KEYCODE_BRIGHTNESS_UP:
			// 监控/拦截/屏蔽亮度加键
			ret = "get Key KEYCODE_BRIGHTNESS_UP(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_MEDIA_PLAY:
			ret = "get Key KEYCODE_MEDIA_PLAY(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_MEDIA_PAUSE:
			ret = "get Key KEYCODE_MEDIA_PAUSE(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
			ret = "get Key KEYCODE_MEDIA_PREVIOUS(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
			ret = "get Key KEYCODE_MEDIA_PLAY_PAUSE(KeyCode:" + keyCode + ")";
			break;
		case KeyEvent.KEYCODE_MEDIA_NEXT:
			ret = "get Key KEYCODE_MEDIA_NEXT(KeyCode:" + keyCode + ")";
			break;
		default:
			ret = "keyCode: "
					+ keyCode
					+ " (http://developer.android.com/reference/android/view/KeyEvent.html)";
			break;
		}
		return ret;
	}
	
	public void printToast(String str) {
		tvShow.setText(str);
	}

更多精彩资讯,请扫码关注。

【记录】Android监听蓝牙耳机的按键事件_第2张图片

你可能感兴趣的:(Android)