Example usage for android.bluetooth.le ScanCallback ScanCallback

List of usage examples for android.bluetooth.le ScanCallback ScanCallback

Introduction

In this page you can find the example usage for android.bluetooth.le ScanCallback ScanCallback.

Prototype

ScanCallback

Source Link

Usage

From source file:com.wolkabout.hexiwear.service.DeviceDiscoveryService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void startLolipopScan() {
    lolipopScanCallback = new ScanCallback() {
        @Override//  w  w w.j a  v  a  2 s .c  om
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            final BluetoothDeviceWrapper wrapper = new BluetoothDeviceWrapper();
            wrapper.setDevice(result.getDevice());
            wrapper.setSignalStrength(result.getRssi());
            onDeviceDiscovered(wrapper);
        }
    };
    bluetoothAdapter.getBluetoothLeScanner().startScan(lolipopScanCallback);
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences = getActivity().getSharedPreferences(Constants.PREFS_NAME, 0);
    arrayList = new ArrayList<>();
    arrayAdapter = new BeaconArrayAdapter(getActivity(), R.layout.beacon_list_item, arrayList);

    scanCallback = new ScanCallback() {
        @Override/*  w w  w .  j  av a  2  s .  c  o  m*/
        public void onScanResult(int callbackType, ScanResult result) {
            ScanRecord scanRecord = result.getScanRecord();
            if (scanRecord == null) {
                Log.w(TAG, "Null ScanRecord for device " + result.getDevice().getAddress());
                return;
            }

            byte[] serviceData = scanRecord.getServiceData(EDDYSTONE_SERVICE_UUID);
            if (serviceData == null) {
                return;
            }

            // We're only interested in the UID frame time since we need the beacon ID to register.
            if (serviceData[0] != EDDYSTONE_UID_FRAME_TYPE) {
                return;
            }

            // Extract the beacon ID from the service data. Offset 0 is the frame type, 1 is the
            // Tx power, and the next 16 are the ID.
            // See https://github.com/google/eddystone/eddystone-uid for more information.
            byte[] id = Arrays.copyOfRange(serviceData, 2, 18);
            if (arrayListContainsId(arrayList, id)) {
                return;
            }

            // Draw it immediately and kick off a async request to fetch the registration status,
            // redrawing when the server returns.
            Log.i(TAG, "id " + Utils.toHexString(id) + ", rssi " + result.getRssi());

            Beacon beacon = new Beacon("EDDYSTONE", id, Beacon.STATUS_UNSPECIFIED, result.getRssi());
            insertIntoListAndFetchStatus(beacon);
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e(TAG, "onScanFailed errorCode " + errorCode);
        }
    };

    createScanner();
}

From source file:io.v.android.libs.discovery.ble.BlePlugin.java

private void updateScanning() {
    if (isScanning && scanCancellationThreads.size() == 0) {
        isScanning = false;//  w  w w.  j av  a  2s.  c  om
        bluetoothLeScanner.stopScan(scanCallback);
        return;
    }

    if (!isScanning && scanCancellationThreads.size() > 0) {
        isScanning = true;
        ScanFilter.Builder builder = new ScanFilter.Builder();
        byte[] manufacturerData = {};
        byte[] manufacturerMask = {};

        builder.setManufacturerData(1001, manufacturerData, manufacturerMask);
        final List<ScanFilter> scanFilter = new ArrayList<>();
        scanFilter.add(builder.build());

        scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                // in L the only value for callbackType is CALLBACK_TYPE_ALL_MATCHES, so
                // we don't look at its value.
                ScanRecord record = result.getScanRecord();
                // Use 1001 to denote that this is a Vanadium device.  We picked an id that is
                // currently not in use.
                byte[] data = record.getManufacturerSpecificData(1001);
                ByteBuffer buffer = ByteBuffer.wrap(data);
                final long hash = buffer.getLong();
                final String deviceId = result.getDevice().getAddress();
                if (cachedDevices.haveSeenHash(hash, deviceId)) {
                    return;
                }
                synchronized (scannerLock) {
                    if (pendingCalls.contains(deviceId)) {
                        Log.d("vanadium", "not connecting to " + deviceId + " because of pending connection");
                        return;
                    }
                    pendingCalls.add(deviceId);
                }
                BluetoothGattClientCallback.Callback ccb = new BluetoothGattClientCallback.Callback() {
                    @Override
                    public void handle(Map<UUID, Map<UUID, byte[]>> services) {
                        Set<Advertisement> advs = new HashSet<>();
                        for (Map.Entry<UUID, Map<UUID, byte[]>> entry : services.entrySet()) {
                            try {
                                Advertisement adv = BleAdvertisementConverter
                                        .bleAttrToVAdvertisement(entry.getValue());
                                advs.add(adv);
                            } catch (IOException e) {
                                Log.e("vanadium", "Failed to convert advertisement" + e);
                            }
                        }
                        cachedDevices.saveDevice(hash, advs, deviceId);
                        synchronized (scannerLock) {
                            pendingCalls.remove(deviceId);
                        }
                        bluetoothLeScanner.startScan(scanFilter,
                                new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(),
                                scanCallback);
                    }
                };
                BluetoothGattClientCallback cb = new BluetoothGattClientCallback(ccb);
                bluetoothLeScanner.stopScan(scanCallback);
                Log.d("vanadium", "connecting to " + result.getDevice());
                result.getDevice().connectGatt(androidContext, false, cb);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
            }

            @Override
            public void onScanFailed(int errorCode) {
            }
        };
        bluetoothLeScanner.startScan(scanFilter,
                new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(), scanCallback);
    }
}

From source file:io.v.android.impl.google.discovery.plugins.ble.Driver.java

private synchronized void startBluetoothLeScanner() {
    if (mLeScanner == null) {
        return;/* w ww . j a v a  2s  .co m*/
    }

    ImmutableList.Builder<ScanFilter> builder = new ImmutableList.Builder();
    for (UUID uuid : mScanUuids) {
        builder.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(uuid)).build());
    }
    List<ScanFilter> filters = builder.build();

    ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();

    // ScanFilter doesn't work with startScan() if there are too many - more than 63bits - ignore
    // bits. So we call startScan() without a scan filter for base/mask uuids and match scan results
    // against it.
    final ScanFilter matcher = new ScanFilter.Builder().setServiceUuid(mScanBaseUuid, mScanMaskUuid).build();

    mLeScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            if (callbackType == ScanSettings.CALLBACK_TYPE_MATCH_LOST) {
                // This callback will never be called with this callback type, since the
                // scan setting is for CALLBACK_TYPE_ALL_MATCHES. But just for safety.
                return;
            }
            if (!matcher.matches(result)) {
                return;
            }
            BluetoothDevice device = result.getDevice();
            synchronized (Driver.this) {
                if (mScanSeens != null && mScanSeens.put(device, result.getRssi()) == null) {
                    mGattReader.readDevice(device);
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e(TAG, "startScan failed: " + errorCode);
        }
    };

    mLeScanner.startScan(filters, settings, mLeScanCallback);
}

From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java

/**
 * Initializes a reference to the local Bluetooth adapter.
 *
 * @return Return true if the initialization is successful.
 *///from   w  w  w  .  ja  v a  2 s  . c om
@SuppressLint("NewApi")
public IoTResultCodes initialize() {

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        //finish();
        return IoTResultCodes.BLE_NOT_SUPPORTED;
    }

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Unable to initialize BluetoothManager.");
            return IoTResultCodes.BLUETOOTH_NOT_SUPPORTED;
        }
    }
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        //finish();
        return IoTResultCodes.BLUETOOTH_NOT_SUPPORTED;
    }
    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) {
        return IoTResultCodes.BLUETOOTH_NOT_ENABLED;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mLeScanLollipopCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                //super.onScanResult(callbackType, result);

                try {
                    BluetoothDevice device = result.getDevice();
                    byte[] scanRecord = result.getScanRecord().getBytes();
                    final HashMap<Integer, AdRecord> adRecords = AdRecord.parseScanRecord(scanRecord);

                    /**
                     * UUID  ? .
                     */
                    ArrayList<String> scannedUuids = DataParser.getUuids(adRecords);
                    if (scannedUuids == null || scannedUuids.size() == 0) {
                        Log.e(TAG, ">>> xx device name " + device.getAddress() + " has no uuid advertisement");
                        return;
                    }

                    IoTDevice iotDevice = new IoTDevice();
                    iotDevice.setDeviceId(device.getAddress());
                    iotDevice.setDeviceName(device.getName());
                    iotDevice.setDeviceType(IoTDevice.DEVICE_TYPE_STRING_BT);

                    iotDevice.setUuids(scannedUuids);
                    iotDevice.setUuidLen(DataParser.getUuidLength(adRecords));

                    iotDevice.setAdRecordHashMap(adRecords);
                    mTempScanedList.put(iotDevice.getDeviceId(), iotDevice);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                //super.onBatchScanResults(results);
                Log.d(TAG, "mScanCallback.. onBatchScanResults");
            }

            @Override
            public void onScanFailed(int errorCode) {
                //super.onScanFailed(errorCode);
                Log.d(TAG, "mScanCallback.. onScanFailed");
            }
        };
    } else {
        mLeScanKitkatCallback = new BluetoothAdapter.LeScanCallback() {

            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                Log.d(TAG, ">> mLeScanKitkatCallback..");

                try {
                    final HashMap<Integer, AdRecord> adRecords = AdRecord.parseScanRecord(scanRecord);
                    /**
                     * UUID  ? .
                     */
                    ArrayList<String> scannedUuids = DataParser.getUuids(adRecords);
                    if (scannedUuids == null || scannedUuids.size() == 0) {
                        Log.e(TAG, ">>> xx device name " + device.getAddress() + " has no uuid advertisement");
                        return;
                    }

                    IoTDevice iotDevice = new IoTDevice();
                    iotDevice.setDeviceId(device.getAddress());
                    iotDevice.setDeviceName(device.getName());
                    iotDevice.setDeviceType(IoTDevice.DEVICE_TYPE_STRING_BT);

                    iotDevice.setUuids(scannedUuids);
                    iotDevice.setUuidLen(DataParser.getUuidLength(adRecords));

                    iotDevice.setAdRecordHashMap(adRecords);
                    mTempScanedList.put(iotDevice.getDeviceId(), iotDevice);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    return IoTResultCodes.SUCCESS;
}