简体   繁体   中英

get two BLE device with onScanResult in android

I tried to get two device name and address inside onScanResult function in Android but I couldn't get these information. As I understand this function call peridicly itself until stop searching and the function give some result about the founded device but I couldn't get how many device found and device information at the same time.

Here is my code :

private ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {

        if("MyBLEdevice".equals(result.getDevice().getName())){
            bleDevice = result.getDevice();
            if(bleScanner !=null){
                bleScanner.stopScan(scanCallback);
            }

        }

        super.onScanResult(callbackType, result);
    }
};

I change my code but I couldn't stop scanResult

boolean isDuplicate = false;
private ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {

        if("MyBLEdevice".equals(result.getDevice().getName())){

            for(BluetoothDevice device : mLeDevices)
            {
                if(device.getAddress().equals(result.getDevice().getAddress())){
                    isDuplicate = true;
                }
                if(!isDuplicate){
                    mLeDevices.add(result.getDevice());
                }
                if(mLeDevices.size()==2)
                {
                    bleScanner.stopScan(scanCallback);
                    bleScanner.flushPendingScanResults(scanCallback);
                }

            }

        }

        super.onScanResult(callbackType, result);
    }
};

You continuously get results, each result is for one device only, from scan even for the same device as soon as new advertisement is send.

To get list with unique devices you should remove duplicates and better choice is to update the device that is already on the list when you receive update for that device.

You can get the 2 specific devices by using device.getName() , make sure that you are advertising names, long names are not send via advertisement, or Service UUIDs by

List<ParcelUuid> parcelUuids = result.getScanRecord().getServiceUuids();

and compare this UUID you created to advertise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM