记一次通过蓝牙键盘触发事件,在对应的Activity复写onKeyUp每次按键或长按保证只触发一次
@Overridepublic boolean onKeyUp(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_TAB: // 右上角“左右切换”按钮...break;case KeyEvent.KEYCODE_NUMPAD_1: // 用户点击 1...break;case KeyEvent.KEYCODE_NUMPAD_2: // 用户点击 2...break;case KeyEvent.KEYCODE_NUMPAD_3: // 用户点击 3...break;case KeyEvent.KEYCODE_NUMPAD_4: // 用户点击 4...break;case KeyEvent.KEYCODE_NUMPAD_5: // 用户点击 5...break;case KeyEvent.KEYCODE_NUMPAD_6: // 用户点击 6...break;case KeyEvent.KEYCODE_NUMPAD_7: // 用户点击 7...break;case KeyEvent.KEYCODE_NUMPAD_8: // 用户点击 8...break;case KeyEvent.KEYCODE_NUMPAD_9: // 点 9...break;case KeyEvent.KEYCODE_NUMPAD_ADD: // 点“+”...break;case KeyEvent.KEYCODE_NUMPAD_SUBTRACT: // 点“-”...break;case KeyEvent.KEYCODE_NUMPAD_ENTER: // 点“⏎”...break;case KeyEvent.KEYCODE_9: // 点“[”...break;case KeyEvent.KEYCODE_0: // 点“]”...break;default:break;}return true;}
注意:不同型号手机事件的keyCode可能不同,例如“=”有可能是KEYCODE_EQUALS或者KEYCODE_NUMPAD_EQUALS
接收系统广播对蓝牙开关以及蓝牙键盘的连接状态进行监听,Activity中动态注册广播
private BluetoothMonitorReceiver bleListenerReceiver = null;private void registerBluetoothMonitorReceiver(){bleListenerReceiver = new BluetoothMonitorReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);registerReceiver(bleListenerReceiver, intentFilter);}
在onDestroy()中解除注册
@Overridepublic void onDestroy() {super.onDestroy();unregisterReceiver(bleListenerReceiver);}
蓝牙状态监听的广播类
public class BluetoothMonitorReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (action != null) {switch (action) {case BluetoothAdapter.ACTION_STATE_CHANGED:int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);switch (blueState) {case BluetoothAdapter.STATE_ON:Toast.makeText(context, "蓝牙已打开", Toast.LENGTH_SHORT).show();break;case BluetoothAdapter.STATE_OFF:Toast.makeText(context, "蓝牙已关闭", Toast.LENGTH_SHORT).show();break;}break;case BluetoothDevice.ACTION_ACL_CONNECTED:Toast.makeText(context, "蓝牙设备:" + device.getName() + "已连接", Toast.LENGTH_SHORT).show();break;case BluetoothDevice.ACTION_ACL_DISCONNECTED:Toast.makeText(context, "蓝牙设备:" + device.getName() + "已断开", Toast.LENGTH_SHORT).show();break;}}}
}
权限(如果需要在程序中开启或关闭蓝牙还需要admin权限)
<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
BLE:一般将蓝牙3.0之前的BR/EDR蓝牙称为传统蓝牙,而将蓝牙4.0规范后的BLE(Bluetooh Low Energy)蓝牙称为低功耗蓝牙。蓝牙低能耗技术是短距离、低成本、可互操作性的无线技术,它利用许多智能手段最大限度地降低功耗。
ACL:蓝牙基带技术支持两种连接类型:同步定向连接(SCO)类型和异步无连接(ACL)类型。前者主要用于同步话音传送,后者主要用于分组数据传送。