最近在学习蓝牙 4.0,看了一下与android ble有关的api,在android手机上写了个小程序,与TI CC2540进行通信,扫描到设备之后进行连接,然后传输数据,传输完毕之后断开连接再进行扫描。大致传输7、8次数据之后,手机端再使用connectGatt()进行连接时,无法进入onConnectionStateChange()回调函数,数据接收无法继续,程序好像是死在这了。但是前面几次都是正常的,假如此时在后台关闭该程序再重新打开,就又可以正常接收数据了。不知道怎么回事,求指点!
程序片段及调试记录如下:
程序片段及调试记录如下:
private void connect(BluetoothDevice device) { if (!isConnected) { handler.removeCallbacks(runnable); mAdapter.stopLeScan(mLeScanCallback); isScaning = false; connectCounter = new Counter(5, "connectCounter", new CounterTask() { @Override public void run() { search(); handler.postDelayed(runnable, GattConstants.POST_PERIOD); } }); connectCounter.start(); bluetoothGatt = device.connectGatt(context, true, gattCallback); Log.d(BLUETOOTH_INFO, "start connect"); } }
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { // TODO Auto-generated method stub super.onConnectionStateChange(gatt, status, newState); Log.d(BLUETOOTH_INFO," In onConnectionStateChange"); if (BluetoothGatt.GATT_SUCCESS == status) { Log.d(BLUETOOTH_INFO,"onConnectionStateChange:status --> success"); } else { Log.d(BLUETOOTH_INFO,"onConnectionStateChange:status --> failed"); } // CQ :status 表示相应的连接或断开操作能否完成,而不是指连接状态 if (newState == BluetoothGatt.STATE_DISCONNECTED) { Log.d(BLUETOOTH_INFO, "onConnectionStateChange --> disconnected"); if (!isConnected) { connectCounter.addCount(); if (connectCounter.getCount() <= connectCounter.getMaxCount()){ gatt.connect(); } } else { if (dataTransferTimer != null){ dataTransferTimer.close(); } gatt.connect(); } } else if (newState == BluetoothGatt.STATE_CONNECTED) { Log.d(BLUETOOTH_INFO, "onConnectionStateChange --> connected"); isConnected = true; connectCounter.close(); gatt.discoverServices(); } }
下面是用记事本保存的Logcat记录片段:
解决方案