jhon snow
jhon snow

Reputation: 91

Android BLE connection disconnects

I am writing an app that scans for ble devices then displays the results in a listview so the user can click on a device to connect. Im having two problems. One is when I stop the Scan and connect to a device the connection is not very good.(The led on the device keeps blinking indicating the connection is being disconnected and reconnected.) The second problem I'm having is that on some phones I get multiple results of the same device in the listview. In the OnLeScan() method I am puting the devices I find into a arraylist to be displayed once the scan is done. How can I fix my issues. I am aware I am using the old APi for 21+

     private BluetoothAdapter.LeScanCallback mLeScanCallback =
     new BluetoothAdapter.LeScanCallback() {
       @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                         byte[] scanRecord) {

         runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mdevices.put(dcount, device);
                names.add(mdevices.get(dcount).getName().toString() + "  " + "MAC:" + mdevices.get(dcount).getAddress() + " " + rssi);
                dcount++;


            }
        });
    }
}; 



 /////////////////////////////



   public void  scanDevice(boolean enable)
   {

  if(enable)
  {

    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < 21) {
                btAdapter.stopLeScan(mLeScanCallback);
            }else
            {
               /// if I comment this out the connection is good
                btAdapter.stopLeScan(mLeScanCallback);
            } 

        }


    }, 1100);


    if (Build.VERSION.SDK_INT < 21) {
        btAdapter.startLeScan(mLeScanCallback);
    } else {

        btAdapter.startLeScan(mLeScanCallback);
    }


}
else
{
    btAdapter.stopLeScan(mLeScanCallback);

}

}

Upvotes: 1

Views: 651

Answers (1)

androholic
androholic

Reputation: 3663

For your first question, it is difficult to say what is causing the disconnects. Maybe the environment you are testing your setup has enough disturbance to cause periodic disconnections. That could be one possibility.

To avoid multiple results of the same device showing up in the ListView, use a HashSet that keeps track of devices already scanned. In your onLeScan callback, check if the device with the given hardware address exists. If not, add it to your ArrayList. Something like this:

private HashSet<String> mLeDevicesScanned = new HashSet<String>();

@Override
public synchronized void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

    if (mLeDevicesScanned.add(device.getAddress())) {
          // Add this device to your ArrayList
    }

}

Also, make sure you clear your HashSet when you refresh the scan.

Upvotes: 1

Related Questions