示例#1
0
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if (BlueToothConstants.BLUETOOTH_ACTION_HANDLE_SERVER.equals(action)) {
     int handle = intent.getIntExtra(BlueToothConstants.EXTRA_HANDLE_TYPE, 0);
     switch (handle) {
       case BlueToothConstants.HANDLE_SERVER_SCAN: // 扫描
         SPUtils.setEBikeAddress(BlueToothService.this, ""); // UI发送的重新扫描,则清除保存的设备
         SPUtils.setEBikeName(BlueToothService.this, "");
         mBluetoothDeviceAddress = "";
         mBlueToothConnction.close();
         startScanBluetoothDevice();
         break;
       case BlueToothConstants.HANDLE_SERVER_CONNECT: // 链接
         mBluetoothDeviceAddress = intent.getStringExtra(BlueToothConstants.EXTRA_DATA);
         connectDevice(mBluetoothDeviceAddress);
         break;
       case BlueToothConstants.HANDLE_SERVER_DISCONNECT: // 断开链接
         SPUtils.setEBikeAddress(BlueToothService.this, ""); // UI发送的重新扫描,则清除保存的设备
         SPUtils.setEBikeName(BlueToothService.this, "");
         disconnect();
         break;
       case BlueToothConstants.HANDLE_SERVER_SYNC: // 同步
         // 默认只有链接上蓝牙才去同步
         if (mBlueToothConnction.getState() == BluetoothConnection.STATE_CONNECTED) {
           syncHistory(); // mark  如果想同步历史记录,则打开此处
         } else { // 没有连接就去扫描,并连接
           startScanBluetoothDevice();
         }
         break;
       case BlueToothConstants.HANDLE_SERVER_SEND_DATA: // 发送数据
         //					simulate();
         Gson gson = new Gson();
         String str = intent.getStringExtra(BlueToothConstants.EXTRA_DATA);
         byte[] data = gson.fromJson(str, byte[].class);
         if (data != null) {
           if (data.length > 0) {
             int cmd = data[0];
             byte[] sendData = new byte[data.length - 1];
             for (int i = 0; i < sendData.length; i++) {
               sendData[i] = data[i + 1];
             }
             if (mBlueToothConnction != null && mReceiveCharacteristic != null) { // 开启数据监听
               LogUtils.i(tag, "监听数据");
               mBlueToothConnction.setCharacteristicNotification(
                   mReceiveCharacteristic, true);
             }
             // mark 加上这个,是因为,如果一设置好监听就发送请求数据包,将得不到数据,所以要做一个延迟处理,设置监听后500毫秒再发送请求数据包
             Message msg = Message.obtain();
             msg.what = cmd;
             msg.obj = sendData;
             sendDataControl.sendMessageDelayed(msg, 500);
           }
         }
         break;
       default:
         break;
     }
   }
 }