/** 停止服务 */ private void stopBLEService() { // Make sure we're not doing discovery anymore if (mBlueToothConnction != null && mReceiveCharacteristic != null) { mBlueToothConnction.setCharacteristicNotification(mReceiveCharacteristic, false); } stopScanBluetoothDevice(); isAppInitBluetooth = false; if (mReConnectThread != null) { mReConnectThread.cancel(); mReConnectThread = null; } if (mRequestDataThread != null) { mRequestDataThread.cancel(); mRequestDataThread = null; } if (mBlueToothConnction != null) { mBlueToothConnction.close(); } // unregister unregisterReceiver(mReceiver); unregisterReceiver(mHandleReceiver); unregisterReceiver(mStateReceiver); unregisterReceiver(mQuitReceiver); unregisterReceiver(mHistoryReceiver); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothDeviceAddress = SPUtils.getEBkieAddress(this); // 设备地址 if (mBlueToothConnction == null) { mBlueToothConnction = new BluetoothConnection(this, mHandler); } boolean isGoon = false; if (mReConnectThread == null) { mReConnectThread = new ReConnectThread(); mReConnectThread.start(); } if (mBlueToothConnction.getState() != BluetoothConnection.STATE_CONNECTED) { // 只要不是在链接的情况下就要重新链接 isGoon = true; sendBleState(BlueToothConstants.BLE_STATE_DISCONNECTED); } else { // 已连接 sendBleState(BlueToothConstants.BLE_STATE_CONNECTED); } LogUtils.i(tag, "isGoon" + isGoon); if (isGoon && stateEnableStep()) { // 客户端自动链接 if (!TextUtils.isEmpty(mBluetoothDeviceAddress)) { sendBleState(BlueToothConstants.BLE_STATE_CONNECTTING); startScanBluetoothDevice(); } else { sendBleState(BlueToothConstants.BLE_STATE_NONE); } } return super.onStartCommand(intent, flags, startId); }