Java Code Examples for android.bluetooth.le.ScanResult#getDevice()

The following examples show how to use android.bluetooth.le.ScanResult#getDevice() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainActivity.java    From Mi365Locker with GNU General Public License v3.0 9 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);

    BluetoothDevice newDevice = result.getDevice();

    int newRssi = result.getRssi();
    String device_name = newDevice.getName();
    String device_address = newDevice.getAddress();
    if(device_name == null)
    {
        return;
    }

    DeviceConnection dev = devices_connections.get(device_address);
    if(dev != null) {
        devicesAdapter.update(newDevice, newRssi, dev.getState());
    } else {
        devicesAdapter.update(newDevice, newRssi, RxBleConnection.RxBleConnectionState.DISCONNECTED);
    }

    String mDeviceAddress = newDevice.getAddress();
    add_device_to_attack(mDeviceAddress);
}
 
Example 2
Source File: PeripheralScannerTest.java    From bitgatt with Mozilla Public License 2.0 8 votes vote down vote up
@Test
public void testConnectionAlreadyInMapDisconnectedScanResult() {
    MockScanResultProvider provider = new MockScanResultProvider(10, -167, -40);
    peripheralScanner.addRssiFilter(-10);
    ScanResult result = provider.getAllResults().get(0);
    FitbitBluetoothDevice device = new FitbitBluetoothDevice(result.getDevice());
    GattConnection conn = new GattConnection(device, mockLooper);
    conn.setMockMode(true);
    conn.setState(GattState.DISCONNECTED);
    gatt.getConnectionMap().put(device, conn);
    NoOpGattCallback cb = new NoOpGattCallback() {

        @Override
        public void onBluetoothPeripheralDiscovered(@NonNull GattConnection connection) {
            Assert.assertEquals(conn, connection);
            gatt.unregisterGattEventListener(this);
        }

    };
    gatt.registerGattEventListener(cb);
    peripheralScanner.populateMockScanResultIndividualValue(ScanSettings.CALLBACK_TYPE_FIRST_MATCH, result);
}
 
Example 3
Source File: RileyLinkBLEScanActivity.java    From AndroidAPS with GNU Affero General Public License v3.0 8 votes vote down vote up
private boolean addDevice(ScanResult result) {

            BluetoothDevice device = result.getDevice();

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

            if (serviceUuids == null || serviceUuids.size() == 0) {
                Log.v(TAG, "Device " + device.getAddress() + " has no serviceUuids (Not RileyLink).");
            } else if (serviceUuids.size() > 1) {
                Log.v(TAG, "Device " + device.getAddress() + " has too many serviceUuids (Not RileyLink).");
            } else {

                String uuid = serviceUuids.get(0).getUuid().toString().toLowerCase();

                if (uuid.equals(GattAttributes.SERVICE_RADIO)) {
                    Log.i(TAG, "Found RileyLink with address: " + device.getAddress());
                    mLeDeviceListAdapter.addDevice(result);
                    return true;
                } else {
                    Log.v(TAG, "Device " + device.getAddress() + " has incorrect uuid (Not RileyLink).");
                }
            }

            return false;
        }
 
Example 4
Source File: DalvikBleService.java    From attach with GNU General Public License v3.0 6 votes vote down vote up
private ScanCallback createDeviceCallback() {
    return new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (devices.values().contains(device)) {
                return;
            }
            String address = device.getAddress();
            String name = device.getName();
            devices.put(address, device);
            if (debug) {
                Log.v(TAG, "BLE discovered device: " + device + " with name: " + name + " and address: " + address);
            }
            scanDeviceDetected(name, address);
        }
    };
}
 
Example 5
Source File: BleManager.java    From FastBle with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BleDevice convertBleDevice(ScanResult scanResult) {
    if (scanResult == null) {
        throw new IllegalArgumentException("scanResult can not be Null!");
    }
    BluetoothDevice bluetoothDevice = scanResult.getDevice();
    int rssi = scanResult.getRssi();
    ScanRecord scanRecord = scanResult.getScanRecord();
    byte[] bytes = null;
    if (scanRecord != null)
        bytes = scanRecord.getBytes();
    long timestampNanos = scanResult.getTimestampNanos();
    return new BleDevice(bluetoothDevice, rssi, bytes, timestampNanos);
}
 
Example 6
Source File: BluetoothGlucoseMeter.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example 7
Source File: ScanResultCompat.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanResultCompat(ScanResult result) {
    mDevice = new BluetoothLeDevice(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), System.currentTimeMillis());//result.getTimestampNanos()
    mScanRecord = new ScanRecordCompat(result.getScanRecord());
    mRssi = result.getRssi();
    mTimestampNanos = System.currentTimeMillis();//result.getTimestampNanos();
}
 
Example 8
Source File: BluetoothScannerImplLollipop.java    From Android-BLE with Apache License 2.0 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    Log.e(TAG, "onScanResult: "+result.getScanRecord().getDeviceName());
    BluetoothDevice device = result.getDevice();
    byte[] scanRecord = result.getScanRecord().getBytes();
    if (scanWrapperCallback != null){
        scanWrapperCallback.onLeScan(device, result.getRssi(), scanRecord);
    }
    if (Ble.options().isParseScanData){
        ScanRecord parseRecord = ScanRecord.parseFromBytes(scanRecord);
        if (parseRecord != null && scanWrapperCallback != null) {
            scanWrapperCallback.onParsedData(device, parseRecord);
        }
    }
}
 
Example 9
Source File: BikeActivity.java    From android with MIT License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);

    BluetoothDevice device = result.getDevice();
    String format = "Name:%s, Mac:%s, Type:%s";
    String msg = String.format(format, result.getDevice(), device.getAddress(), device.getType());
    print(msg);
}
 
Example 10
Source File: BluetoothGlucoseMeter.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example 11
Source File: MainActivity.java    From bluetooth with Apache License 2.0 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    if (result == null
        || result.getDevice() == null
        || TextUtils.isEmpty(result.getDevice().getName()))
        return;

    StringBuilder builder = new StringBuilder(result.getDevice().getName());

    builder.append("\n").append(new String(result.getScanRecord().getServiceData(result.getScanRecord().getServiceUuids().get(0)), Charset.forName("UTF-8")));

    mText.setText(builder.toString());
}
 
Example 12
Source File: PeripheralScannerTest.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testConnectionAlreadyInMapScannedPropertiesChangedScanRecord() {
    MockScanResultProvider provider = new MockScanResultProvider(10, -167, -40);
    peripheralScanner.addRssiFilter(-10);
    ScanResult result = provider.getAllResults().get(0);
    FitbitBluetoothDevice device = new FitbitBluetoothDevice(result.getDevice());
    device.setScanRecord(result.getScanRecord());
    GattConnection conn = new GattConnection(device, mockLooper);
    conn.setMockMode(true);
    conn.setState(GattState.DISCONNECTED);
    gatt.getConnectionMap().put(device, conn);
    FitbitBluetoothDevice.DevicePropertiesChangedCallback propChanged = device1 -> Assert.assertNull(device1.getScanRecord());
    device.addDevicePropertiesChangedListener(propChanged);
    device.setScanRecord(null);
    device.removeDevicePropertiesChangedListener(propChanged);
    NoOpGattCallback cb = new NoOpGattCallback() {

        @Override
        public void onBluetoothPeripheralDiscovered(@NonNull GattConnection connection) {
            Assert.assertEquals(conn, connection);
            gatt.unregisterGattEventListener(this);
        }

    };
    gatt.registerGattEventListener(cb);
    gatt.addScannedDevice(device);
}
 
Example 13
Source File: PeripheralScannerTest.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testConnectionAlreadyInMapScannedPropertiesChangedName() {
    MockScanResultProvider provider = new MockScanResultProvider(10, -167, -40);
    peripheralScanner.addRssiFilter(-10);
    ScanResult result = provider.getAllResults().get(0);
    FitbitBluetoothDevice device = new FitbitBluetoothDevice(result.getDevice());
    device.setScanRecord(result.getScanRecord());
    GattConnection conn = new GattConnection(device, mockLooper);
    conn.setMockMode(true);
    conn.setState(GattState.DISCONNECTED);
    gatt.getConnectionMap().put(device, conn);
    FitbitBluetoothDevice.DevicePropertiesChangedCallback propChanged = device1 -> Assert.assertEquals("Yogurt", device1.getName());
    device.addDevicePropertiesChangedListener(propChanged);
    device.setName("Yogurt");
    device.removeDevicePropertiesChangedListener(propChanged);
    NoOpGattCallback cb = new NoOpGattCallback() {

        @Override
        public void onBluetoothPeripheralDiscovered(@NonNull GattConnection connection) {
            Assert.assertEquals(conn, connection);
            gatt.unregisterGattEventListener(this);
        }

    };
    gatt.registerGattEventListener(cb);
    gatt.addScannedDevice(device);
}
 
Example 14
Source File: FitbitGatt.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will add a device that was discovered via the background scan in a provided scan result to
 * the connected devices map and will notify listeners of the availability of the new connection.  This will allow
 * an API user to add devices from scans that occur outside of the context of the periodical scanner.
 *
 * @param result The scan result from the background system scan
 */
@SuppressWarnings({"unused", "WeakerAccess"}) // API Method
public synchronized void addBackgroundScannedDeviceConnection(@Nullable ScanResult result) {
    if (result != null) {
        BluetoothDevice bluetoothDevice = result.getDevice();
        FitbitBluetoothDevice device = new FitbitBluetoothDevice(bluetoothDevice);
        device.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED;
        device.setRssi(result.getRssi());
        addScannedDevice(device);
    } else {
        Timber.w("No result provided.");
    }
}
 
Example 15
Source File: BleScanner.java    From esp-idf-provisioning-android with Apache License 2.0 4 votes vote down vote up
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void onScanResult(int callbackType, ScanResult result) {

    String deviceName = result.getDevice().getName();

    if (result.getDevice() != null && !TextUtils.isEmpty(deviceName)) {

        Log.d(TAG, "========== Device Found : " + deviceName);

        if (TextUtils.isEmpty(prefix)) {

            bleScanListener.onPeripheralFound(result.getDevice(), result);

        } else if (deviceName.startsWith(prefix)) {

            bleScanListener.onPeripheralFound(result.getDevice(), result);
        }
    }
}
 
Example 16
Source File: BluetoothLEScanCallback21.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
public void onScanResult(int callbackType, ScanResult result) {
    //CallsCounter.logCounter(context, "BluetoothLEScanCallback21.onScanResult", "BluetoothLEScanCallback21.onScanResult");

    final BluetoothDevice _device = result.getDevice();

    if (_device == null)
        return;

    //final Context appContext = context.getApplicationContext();

    if (!PPApplication.getApplicationStarted(true))
        // application is not started
        return;
    if (ApplicationPreferences.prefForceOneBluetoothScan != BluetoothScanner.FORCE_ONE_SCAN_FROM_PREF_DIALOG) {
        if (!ApplicationPreferences.applicationEventBluetoothEnableScanning)
            // scanning is disabled
            return;
    }

    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "xxx");

    //boolean scanStarted = (BluetoothScanWorker.getWaitForLEResults(context));
    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "scanStarted=" + scanStarted);

    //if (scanStarted) {
    //PPApplication.logE("BluetoothLEScanCallback21", "onScanResult - callbackType=" + callbackType);
    //PPApplication.logE("BluetoothLEScanCallback21", "onScanResult - result=" + result.toString());

    //String btAddress = _device.getAddress();
    String btName = _device.getName();
    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "deviceAddress=" + btAddress);
    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "deviceName=" + btName);

    BluetoothDeviceData deviceData = new BluetoothDeviceData(btName, _device.getAddress(),
            BluetoothScanWorker.getBluetoothType(_device), false, 0, false, true);

    BluetoothScanWorker.addLEScanResult(deviceData);

    /*
    PPApplication.startHandlerThreadBluetoothLECallback();
    final Handler handler = new Handler(PPApplication.handlerThreadBluetoothLECallback.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = null;
            try {
                if (powerManager != null) {
                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":BluetoothLEScanBroadcastReceiver21_onScanResult");
                    wakeLock.acquire(10 * 60 * 1000);
                }

                //PPApplication.logE("PPApplication.startHandlerThread", "START run - from=BluetoothLEScanCallback21.onScanResult");

                //boolean scanStarted = (BluetoothScanWorker.getWaitForLEResults(context));
                //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "scanStarted=" + scanStarted);

                //if (scanStarted) {
                    //PPApplication.logE("BluetoothLEScanCallback21", "onScanResult - callbackType=" + callbackType);
                    //PPApplication.logE("BluetoothLEScanCallback21", "onScanResult - result=" + result.toString());

                    //String btAddress = _device.getAddress();
                    String btName = _device.getName();
                    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "deviceAddress=" + btAddress);
                    //PPApplication.logE("BluetoothLEScanCallback21.onScanResult", "deviceName=" + btName);

                    BluetoothDeviceData deviceData = new BluetoothDeviceData(btName, _device.getAddress(),
                            BluetoothScanWorker.getBluetoothType(_device), false, 0, false, true);

                    BluetoothScanWorker.addLEScanResult(deviceData);
                //}

                //PPApplication.logE("PPApplication.startHandlerThread", "END run - from=BluetoothLEScanCallback21.onScanResult");
            } finally {
                if ((wakeLock != null) && wakeLock.isHeld()) {
                    try {
                        wakeLock.release();
                    } catch (Exception ignored) {}
                }
            }
        }
    });
    */
}
 
Example 17
Source File: InternalScanResultCreator.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public RxBleInternalScanResult create(ScanResult result) {
    final ScanRecordImplNativeWrapper scanRecord = new ScanRecordImplNativeWrapper(result.getScanRecord());
    return new RxBleInternalScanResult(result.getDevice(), result.getRssi(), result.getTimestampNanos(), scanRecord,
            ScanCallbackType.CALLBACK_TYPE_BATCH);
}
 
Example 18
Source File: InternalScanResultCreator.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public RxBleInternalScanResult create(int callbackType, ScanResult result) {
    final ScanRecordImplNativeWrapper scanRecord = new ScanRecordImplNativeWrapper(result.getScanRecord());
    return new RxBleInternalScanResult(result.getDevice(), result.getRssi(), result.getTimestampNanos(), scanRecord,
            toScanCallbackType(callbackType));
}
 
Example 19
Source File: LollipopPeripheral.java    From react-native-ble-manager with Apache License 2.0 4 votes vote down vote up
public LollipopPeripheral(ReactContext reactContext, ScanResult result) {
	super(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext);
	this.advertisingData = result.getScanRecord();
	this.scanResult = result;
}
 
Example 20
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private void initScanCallback(){
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                UserError.Log.i(TAG, "result: " + result.toString());
                BluetoothDevice btDevice = result.getDevice();
//                // Check if the device has a name, the Dexcom transmitter always should. Match it with the transmitter id that was entered.
//                // We get the last 2 characters to connect to the correct transmitter if there is more than 1 active or in the room.
//                // If they match, connect to the device.
                if (btDevice.getName() != null) {
                    String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                    String deviceNameLastTwo = Extensions.lastTwoCharactersOfString(btDevice.getName());

                    if (transmitterIdLastTwo.equals(deviceNameLastTwo)) {
                        if (advertiseTimeMS.size() > 0)
                            if ((new Date().getTime() - advertiseTimeMS.get(advertiseTimeMS.size()-1)) > 2.5*60*1000)
                                advertiseTimeMS.clear();
                        advertiseTimeMS.add(new Date().getTime());
                        isIntialScan = false;
                        //device = btDevice;
                        device = mBluetoothAdapter.getRemoteDevice(btDevice.getAddress());
                        static_device_address = btDevice.getAddress();
                        stopScan();
                        connectToDevice(btDevice);
                    } else {
                        //stopScan(10000);
                    }
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    UserError.Log.e(TAG, "Already Scanning: " + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2){
                    cycleBT();
                }
            }
        };
    }