Java Code Examples for android.bluetooth.le.ScanResult

The following are top voted examples for showing how to use android.bluetooth.le.ScanResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SensorTag-Accelerometer   File: ScanFragment.java   Source Code and License 9 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // initialize the right scan callback for the current API level
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                mRecyclerViewAdapter.addDevice(result.getDevice().getAddress());
            }
        };
    } else {
        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                mRecyclerViewAdapter.addDevice(bluetoothDevice.getAddress());
            }
        };
    }

    // initialize bluetooth manager & adapter
    BluetoothManager manager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = manager.getAdapter();
}
 
Example 2
Project: PhoneProfilesPlus   File: BluetoothLEScanCallback21.java   Source Code and License 8 votes vote down vote up
public void onBatchScanResults(List<ScanResult> results) {
    CallsCounter.logCounter(context, "BluetoothLEScanCallback21.onBatchScanResults", "BluetoothLEScanCallback21.onBatchScanResults");

    boolean scanStarted = (BluetoothScanJob.getWaitForLEResults(context));

    if (scanStarted) {
        for (ScanResult result : results) {
            //PPApplication.logE("BluetoothLEScanCallback21", "onBatchScanResults - result=" + result.toString());

            BluetoothDevice device = result.getDevice();
            String btName = device.getName();
            PPApplication.logE("BluetoothLEScanCallback21", "onBatchScanResults - deviceName=" + btName);

            BluetoothDeviceData deviceData = new BluetoothDeviceData(btName, device.getAddress(),
                    BluetoothScanJob.getBluetoothType(device), false, 0);

            BluetoothScanJob.addLEScanResult(deviceData);
        }
    }
}
 
Example 3
Project: KB_1711   File: MainActivity.java   Source Code and License 7 votes vote down vote up
private ScanCallback initCallbacks() {
    return new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            if (result != null && result.getDevice() != null) {
                if (isAdded(result.getDevice())) {
                    // No add
                } else {
                    saveDevice(result.getDevice());
                }
            }

        }

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

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 4
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   Source Code and License 7 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BluetoothLeScanL21Proxy(BluetoothAdapter bluetoothAdapter) {

    mBluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();

    mLeScanCallback = new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
        }

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

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 5
Project: ITagAntiLost   File: NewDevicePresenter.java   Source Code and License 7 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
  super.onScanResult(callbackType, result);
  if (result.getScanRecord() != null) {
    List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
    if (uuids != null) {
      for (ParcelUuid uuid : uuids) {
        if (uuid.getUuid().equals(BleService.FIND_ME_SERVICE)) {
          if (!currentAddresses.contains(result.getDevice().getAddress()))
            viewStatePublisher.onNext(
                new NewDevicesViewState.NewDeviceState(
                    result.getDevice().getAddress(),
                    result.getScanRecord().getDeviceName())
            );
          break;
        }
      }
    }
  }
}
 
Example 6
Project: miband-android   File: MiBand.java   Source Code and License 7 votes vote down vote up
/**
 * Stops scanning for devices
 *
 * @return An Observable which emits ScanResult
 */
public Observable<ScanResult> stopScan() {
    return Observable.create(subscriber -> {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.stopScan(getScanCallback(subscriber));
            } else {
                Log.e(TAG, "BluetoothLeScanner is null");
                subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
            }
        } else {
            Log.e(TAG, "BluetoothAdapter is null");
            subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
        }
    });
}
 
Example 7
Project: AndroidSDK2.0   File: DeviceListActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    BluetoothDevice device = result.getDevice();
    if ( device != null )
    {
        String msg = device.getName() + "\n" +"[RSSI : " + result.getRssi() + "dBm]" + device.getAddress();
        NLog.d( "onLeScan " + msg );

        /**
         * setting pen client control for ble
         */
            if(!temp.contains( device.getAddress() ))
            {
                NLog.d( "ACTION_FOUND onLeScan : " +device.getName() + " address : "+ device.getAddress()+", COD:" + device.getBluetoothClass());
                temp.add( device.getAddress());
                mNewDevicesArrayAdapter.add(msg);
            }
    }
}
 
Example 8
Project: plen-Scenography_Android   File: PlenConnectionActivityPresenter.java   Source Code and License 6 votes vote down vote up
public void onEvent(@NonNull PlenScanService.StateTransitionEvent event) {
    mView.ifPresent(fragment -> {
        switch (event.getNewState()) {
            case SCANNING:
                fragment.notifyPlenScanning();
                break;
            case STOP:
                if (!mScanResults.isPresent()) {
                    fragment.notifyPlenScanCancel();
                } else {
                    List<String> addresses = Observable.from(mScanResults.get())
                            .map(ScanResult::getDevice)
                            .map(BluetoothDevice::getAddress)
                            .distinct().toList().toBlocking().single();
                    fragment.notifyPlenScanComplete(addresses);
                }
                break;
        }
    });
}
 
Example 9
Project: react-native-ble-manager   File: LollipopScanManager.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(final int callbackType, final ScanResult result) {

	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			Log.i(bleManager.LOG_TAG, "DiscoverPeripheral: " + result.getDevice().getName());
			String address = result.getDevice().getAddress();
                  Peripheral peripheral = null;

			if (!bleManager.peripherals.containsKey(address)) {
				peripheral = new Peripheral(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext);
				bleManager.peripherals.put(address, peripheral);
			} else {
				peripheral = bleManager.peripherals.get(address);
				peripheral.updateRssi(result.getRssi());
				peripheral.updateData(result.getScanRecord().getBytes());
			}

			WritableMap map = peripheral.asWritableMap();
			bleManager.sendEvent("BleManagerDiscoverPeripheral", map);
		}
	});
}
 
Example 10
Project: ProjectPlutoAndroid   File: ScanActivity.java   Source Code and License 6 votes vote down vote up
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ScanResult scanResult = getItem(position);
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext())
                .inflate(R.layout.list_item_scanresult, parent, false);
    }

    TextView name = (TextView)convertView.findViewById(R.id.scan_result_name);
    name.setText(scanResult.getDevice().getName());
    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mScanPresenter.onClickConnect(getItem(position));
        }
    });

    return convertView;
}
 
Example 11
Project: ProjectPlutoAndroid   File: BleScannerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testScanForBleDevices() {
    ScanResult savedResult = mock(ScanResult.class);
    Map<String, ScanResult> resultMap = new HashMap<>();
    resultMap.put("EB:22:19:0E:B2:01", savedResult);
    mScanner.mAddressToScanResult = resultMap;

    mScanner.scanForBleDevices();

    verify(mHandler, times(1)).removeCallbacks(mScanner.mStopScanAction);
    verify(mAndroidScanner, times(1)).stopScan(mScanner.mScanCallback);
    assertTrue(resultMap.size() == 0); // make sure saved result was cleared

    verify(mAndroidScanner, times(1)).startScan(mScanner.mScanCallback);
    verify(mHandler, times(1))
            .postDelayed(mScanner.mStopScanAction, BleScanner.BLE_SCAN_DURATION_MS);
}
 
Example 12
Project: ProjectPlutoAndroid   File: ScanActivityTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetListItemView() {
    activity.mScanPresenter = presenter;
    ScanResult result = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    doReturn(device).when(result).getDevice();
    doReturn("testName").when(device).getName();
    activity.mAdapter.add(result);
    View view = activity.mAdapter.getView(0, null, null);
    view.callOnClick();

    verify(presenter, times(1)).onClickConnect(result);
    TextView name = (TextView)view.findViewById(R.id.scan_result_name);
    assertEquals("testName", name.getText());

}
 
Example 13
Project: u2f-ble-test   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
	super.onScanResult(callbackType, result);
	if (devices != null) {
		BluetoothDevice device = result.getDevice();				
		/*
		if ((device.getName() != null) && !devices.containsKey(device.getAddress())) {
			debug("New device detected " + device.getAddress() + " " + device.getName());
			if (device.getName().toUpperCase().contains("U2F")) {					
				devices.put(device.getAddress(), device);
			}
		}
		*/
		if (!devices.containsKey(device.getAddress())) {
			debug("New device detected " + device.getAddress() + "/" + (device.getName() != null ? device.getName() : ""));					
			devices.put(device.getAddress(), device);
		}				
	}
}
 
Example 14
Project: BLE-Mesh   File: BLEGattClients.java   Source Code and License 6 votes vote down vote up
/**
 * callback from BLECentral
 *
 * @param callbackType
 * @param scanResult
 */
@Override
public void onScan(int callbackType, ScanResult scanResult) {
    if (connectedDevices.containsKey(scanResult.getDevice().getAddress())) {
        // If we're already connected, forget it
        //Timber.d("Denied connection. Already connected to  " + scanResult.getDevice().getAddress());
        return;
    }

    if (centralScannedDevices.contains(scanResult.getDevice().getAddress())) {
        // If we're already connected, forget it
        //Timber.d("Denied connection. Already connecting to  " + scanResult.getDevice().getAddress());
        return;
    }

    centralScannedDevices.add(scanResult.getDevice().getAddress());
    Timber.d("GATT Initiating connection to " + scanResult.getDevice().getAddress());
    scanResult.getDevice().connectGatt(context, false, getGattCallback());
}
 
Example 15
Project: FastBle   File: BleManager.java   Source Code and License 6 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 16
Project: miband-android   File: MiBand.java   Source Code and License 6 votes vote down vote up
/**
 * Starts scanning for devices
 *
 * @return An Observable which emits ScanResult
 */
public Observable<ScanResult> startScan() {
    return Observable.create(subscriber -> {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.startScan(getScanCallback(subscriber));
            } else {
                Log.e(TAG, "BluetoothLeScanner is null");
                subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
            }
        } else {
            Log.e(TAG, "BluetoothAdapter is null");
            subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
        }
    });
}
 
Example 17
Project: miband-android   File: ScanActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Handles the result of scanning
 *
 * @return Action handler
 */
private Consumer<ScanResult> handleScanResult() {
    return result -> {
        BluetoothDevice device = result.getDevice();
        Timber.d("Scan results: name:" + device.getName() + ",uuid:"
                + Arrays.toString(device.getUuids()) + ",add:"
                + device.getAddress() + ",type:"
                + device.getType() + ",bondState:"
                + device.getBondState() + ",rssi:" + result.getRssi());

        String item = device.getName() + "|" + device.getAddress();
        if (!mDevices.containsKey(item)) {
            mDevices.put(item, device);
            mAdapter.add(item);
        }
    };
}
 
Example 18
Project: UdooWtf   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    BluetoothDevice device = result.getDevice();
    Log.d(TAG, "scaning finished: "+device);
    if (device != null) {
        int toRemove = -1;
        for (int i = 0; i < beaconList.size(); i++) {
            if (device.getAddress().equals(beaconList.get(i).getMac())) {
                toRemove = i;
            }
        }

        if (toRemove != -1) {
            beaconList.remove(toRemove);

        }


    }
}
 
Example 19
Project: BluetoothCompat   File: ScanResultCompat.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanResultCompat(ScanResult result) {
    mDevice = result.getDevice();
    mScanRecord = new ScanRecordCompat(result.getScanRecord());
    mRssi = result.getRssi();
    mTimestampNanos = result.getTimestampNanos();
}
 
Example 20
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void concludesAtLimit() {
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    criteria.setLimit(1);
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(Subscribers.empty());
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device = Testing.createMockDevice();
    final ScanResult scanResult = new ScanResult(device,
                                                  Testing.EMPTY_SCAN_RECORD,
                                                  Testing.RSSI_DECENT,
                                                  SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult);

    scanner.onConcludeScan();

    assertThat(shadowScanner.getScanCallbacks(), not(hasItem(scanner)));
}
 
Example 21
Project: Freeweight   File: BluetoothAndroid.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result)
{
    BluetoothDevice device = result.getDevice();
    String mac_address = device.getAddress();

    boolean foundOurDevice = false;
    for (int i = 0; i < NUM_WORKOUTS; i++)
    {
        if (Gym.get(i).getMac_address().equals(mac_address) && Gym.get(i).getRSSI() == errorValue)
        {
            Gym.get(i).setRSSI(result.getRssi());
            Log.i(DEBUG, "Found one of our devices: " + mac_address);
            foundOurDevice = true;
            break;
        }
    }

    if (!foundOurDevice)
        Log.i(DEBUG, "Found another Bluetooth device.");
}
 
Example 22
Project: eddystone-android   File: Beacon.java   Source Code and License 6 votes vote down vote up
protected static Beacon beaconFromScanResult(ScanResult scanResult) {
    ScanRecord scanRecord = scanResult.getScanRecord();
    if (scanRecord == null) {
        return null;
    }
    FrameType type;
    Integer txPower;
    double rssi = scanResult.getRssi();
    byte[] bytes = scanRecord.getServiceData(EDDYSTONE_SPEC);
    String identifier = scanResult.getDevice().getAddress();

    txPower = txPowerFromBytes(bytes);

    if (txPower != null) {
        Beacon beacon = new Beacon(rssi, txPower, identifier);
        beacon.parseScanResult(scanResult);
        return beacon;
    }

    return null;
}
 
Example 23
Project: SuperPanel   File: Ble.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);

    BluetoothDevice device = result.getDevice();

    System.out.println("I see a bluetooth device: " + device.getAddress());

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

    if(uuids != null) {
        for (ParcelUuid uuid :uuids) {
            System.out.println("Service UUID: " + uuid.getUuid());
        }
    }

    device.connectGatt(context, false, gattCallback);
}
 
Example 24
Project: myo-emg-visualizer   File: MyoListFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    BluetoothDevice device = result.getDevice();
    String deviceAddress = device.getAddress();
    String deviceName = device.getName();

    String msg = "name=" + device.getName() + ", bondStatus="
            + device.getBondState() + ", address="
            + device.getAddress() + ", type" + device.getType();
    Log.d(TAG, msg);

    Pair<String, String> foundDevice = new Pair<>(deviceName, deviceAddress);
    if (!deviceList.contains(foundDevice)) {
        deviceList.add(foundDevice);
    }
}
 
Example 25
Project: proximity-manager   File: BeaconRegisterActivity.java   Source Code and License 6 votes vote down vote up
private void processResult(ScanResult result) {
    ScanRecord record = result.getScanRecord();
    if (record == null || record.getServiceData(UID_SERVICE) == null) {
        Log.w(TAG, "Invalid Eddystone scan result.");
        return;
    }

    //Convert scan result into an AdvertisedId
    Beacon.AdvertisedId advertisedId =
            Beacon.AdvertisedId.fromAdvertisement(record.getServiceData(UID_SERVICE));
    final Beacon discovered = new Beacon(advertisedId, Beacon.Status.STATUS_UNSPECIFIED);
    //Scan callbacks are not on the main thread
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //Notify the adapter, and get beacon resource from API
            boolean added = mAdapter.addDiscoveredBeacon(discovered);
            if (added) {
                mProximityApi.getBeacon(discovered.advertisedId);
            }
        }
    });
}
 
Example 26
Project: PhoneProfilesPlus   File: BluetoothLEScanCallback21.java   Source Code and License 6 votes vote down vote up
public void onScanResult(int callbackType, ScanResult result) {
    CallsCounter.logCounter(context, "BluetoothLEScanCallback21.onScanResult", "BluetoothLEScanCallback21.onScanResult");

    boolean scanStarted = (BluetoothScanJob.getWaitForLEResults(context));

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

        BluetoothDevice device = result.getDevice();
        String btName = device.getName();
        PPApplication.logE("BluetoothLEScanCallback21", "onScanResult - deviceName=" + btName);

        BluetoothDeviceData deviceData = new BluetoothDeviceData(btName, device.getAddress(),
                BluetoothScanJob.getBluetoothType(device), false, 0);

        BluetoothScanJob.addLEScanResult(deviceData);
    }
}
 
Example 27
Project: android-ble   File: BleScannerL.java   Source Code and License 6 votes vote down vote up
private static android.bluetooth.le.ScanCallback createCallback(ScanCallback scanCallback) {
    return new android.bluetooth.le.ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {

            BluetoothDevice device = result.getDevice();
            int rssi = result.getRssi();
            byte[] scanRecord = (result.getScanRecord() != null ? result.getScanRecord().getBytes() : null);
            scanCallback.onDeviceFound(device, rssi, scanRecord);

            super.onScanResult(callbackType, result);
        }

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

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 28
Project: android-ble   File: BTLEScannerOld.java   Source Code and License 6 votes vote down vote up
public BTLEScannerOld(BluetoothAdapter bluetoothAdapter, Callback callback) {
    this.bluetoothAdapter = bluetoothAdapter;
    this.leScanCallback = callback::onScan;

    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        this.leScanner = bluetoothAdapter.getBluetoothLeScanner();

        this.scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
                    callback.onScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
                }

                super.onScanResult(callbackType, result);
            }
        };
    } else {
        this.leScanner = null;
        this.scanCallback = null;
    }
}
 
Example 29
Project: android-ble   File: BTLEScannerOld.java   Source Code and License 6 votes vote down vote up
public void startScan() {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        leScanner.startScan(new android.bluetooth.le.ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {

                super.onScanResult(callbackType, result);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                super.onBatchScanResults(results);
            }
        });
    } else {
        bluetoothAdapter.startLeScan(leScanCallback);
    }
}
 
Example 30
Project: react-native-ble   File: RNBLEModule.java   Source Code and License 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    boolean isDuplicate = false;

    //filter out duplicate entries if requested
    if(!rnbleModule.allowDuplicates){                
        for(String s : scannedDeviceAddresses){
            BluetoothDevice device = result.getDevice();
            String address = device.getAddress();

            if(s.equals(address)) {
               isDuplicate = true;
               break;
            }
        }
    }

    if(!isDuplicate){  
        scannedDeviceAddresses.add(result.getDevice().getAddress());
        super.onScanResult(callbackType, result);
        processScanResult(result);
    }
}
 
Example 31
Project: android-beacon-library   File: ScanJobScheduler.java   Source Code and License 6 votes vote down vote up
public void scheduleAfterBackgroundWakeup(Context context, List<ScanResult> scanResults) {
    if (scanResults != null) {
        mBackgroundScanResultQueue.addAll(scanResults);
    }
    synchronized (this) {
        // We typically get a bunch of calls in a row here, separated by a few millis.  Only do this once.
        if (System.currentTimeMillis() - mScanJobScheduleTime > MIN_MILLIS_BETWEEN_SCAN_JOB_SCHEDULING) {
            LogManager.d(TAG, "scheduling an immediate scan job because last did "+(System.currentTimeMillis() - mScanJobScheduleTime)+"seconds ago.");
            mScanJobScheduleTime = System.currentTimeMillis();
        }
        else {
            LogManager.d(TAG, "Not scheduling an immediate scan job because we just did recently.");
            return;
        }
    }
    ScanState scanState = ScanState.restore(context);
    schedule(context, scanState, true);
}
 
Example 32
Project: mDL-ILP   File: BTConnection.java   Source Code and License 5 votes vote down vote up
@NonNull
private ScanCallback getScanCallback(final byte[] serviceData) {
    return new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                processResult(result);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult s: results) {
                    processResult(s);
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.d(TAG, "Scan failed: " + String.valueOf(errorCode));
            }

            public void processResult(ScanResult sr) {
                Log.d(TAG, "Found device " + sr.getDevice().getName() + "(" + sr.getDevice().getAddress() + ")");

                /* confirm correct connection key */
                byte[] sd = sr.getScanRecord().getServiceData(Constants.SERVICE_pUUID);
                if (sd != null) {
                    if (Arrays.equals(sd, serviceData)) {
                        BTConnection.this.stopScan();
                        transfer.startServer(sr.getDevice());
                    } else {
                        Log.d(TAG, "Incorrect service data: " + new String(sd) + " instead of " + new String(serviceData) + ". Continuing.");
                    }
                } else {
                    Log.d(TAG, "No service data received -- continuing.");
                }
            }
        };
}
 
Example 33
Project: android-ponewheel   File: BluetoothUtilImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    String deviceName = result.getDevice().getName();
    String deviceAddress = result.getDevice().getAddress();

    Log.i(TAG, "ScanCallback.onScanResult: " + mScanResults.entrySet());
    if (!mScanResults.containsKey(deviceAddress)) {
        Log.i(TAG, "ScanCallback.deviceName:" + deviceName);
        mScanResults.put(deviceAddress, deviceName);

        if (deviceName == null) {
            updateLog("Found " + deviceAddress);
        } else {
            updateLog("Found " + deviceAddress + " (" + deviceName + ")");
        }

        if (deviceName != null && (deviceName.startsWith("ow") || deviceName.startsWith("Onewheel"))) {
            updateLog("Looks like we found our OW device (" + deviceName + ") discovering services!");
            connectToDevice(result.getDevice());
        } else {
            Timber.d("onScanResult: found another device:" + deviceName + "-" + deviceAddress);
        }

    } else {
        Timber.d("onScanResult: mScanResults already had our key.");
    }


}
 
Example 34
Project: AndroidSDK2.0   File: DeviceListActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onBatchScanResults(List<ScanResult> results) {
    super.onBatchScanResults(results);
    for ( ScanResult scanResult : results ) {
        NLog.d("ScanResult - Results", scanResult.toString());
    }
}
 
Example 35
Project: KB_1711   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private ScanCallback initCallbacks() {
    return new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            if (result != null && result.getDevice() != null) {
                if (isAdded(result.getDevice())) {
                    // No add
                } else {
                    saveDevice(result.getDevice());
                }
            }

        }

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

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 36
Project: mobly-bundled-snippets   File: BluetoothLeScannerSnippet.java   Source Code and License 5 votes vote down vote up
public void onScanResult(int callbackType, ScanResult result) {
    Log.i("Got Bluetooth LE scan result.");
    SnippetEvent event = new SnippetEvent(mCallbackId, "onScanResult");
    String callbackTypeString =
            MbsEnums.BLE_SCAN_RESULT_CALLBACK_TYPE.getString(callbackType);
    event.getData().putString("CallbackType", callbackTypeString);
    event.getData().putBundle("result", mJsonSerializer.serializeBleScanResult(result));
    mEventCache.postEvent(event);
}
 
Example 37
Project: mobly-bundled-snippets   File: BluetoothLeScannerSnippet.java   Source Code and License 5 votes vote down vote up
public void onBatchScanResults(List<ScanResult> results) {
    Log.i("Got Bluetooth LE batch scan results.");
    SnippetEvent event = new SnippetEvent(mCallbackId, "onBatchScanResult");
    ArrayList<Bundle> resultList = new ArrayList<>(results.size());
    for (ScanResult result : results) {
        resultList.add(mJsonSerializer.serializeBleScanResult(result));
    }
    event.getData().putParcelableArrayList("results", resultList);
    mEventCache.postEvent(event);
}
 
Example 38
Project: sdc-1-quickstart-android   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Callback when a BLE advertisement has been found.
 *
 * @param callbackType Determines how this callback was triggered.
 * @param result       A Bluetooth LE scan result.
 */
@Override
public void onScanResult(int callbackType, final ScanResult result) {
    super.onScanResult(callbackType, result);

    // Get the ScanRecord and check if it is defined (is nullable)
    final ScanRecord scanRecord = result.getScanRecord();
    if (scanRecord != null) {
        // Check if the Service UUIDs are defined (is nullable) and contain the discovery
        // UUID
        final List<ParcelUuid> serviceUuids = scanRecord.getServiceUuids();
        if (serviceUuids != null && serviceUuids.contains(DISCOVERY_UUID)) {
            // We have found our device, so update the GUI, stop scanning and start
            // connecting
            final BluetoothDevice device = result.getDevice();

            // We'll make sure the GUI is updated on the UI thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // At this point we have the device address and RSSI, so update those
                    deviceAddressTextView.setText(device.getAddress());
                    rssiTextView.setText(getString(R.string.rssi, result.getRssi()));
                }
            });

            stopDiscovery();

            bluetoothGatt = device.connectGatt(
                    MainActivity.this,
                    // False here, as we want to directly connect to the device
                    false,
                    bluetoothGattCallback
            );
        }
    }
}
 
Example 39
Project: AndroidMuseumBleManager   File: ScanResultCompat.java   Source Code and License 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 40
Project: AndroidMuseumBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    ScanCallbackCompat callbackCompat = callbackCompatRef.get();
    if (callbackCompat != null) {
        callbackCompat.onScanResult(callbackType, new ScanResultCompat(result));
    }
}
 
Example 41
Project: AndroidMuseumBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 5 votes vote down vote up
@Override
public void onBatchScanResults(List<ScanResult> results) {
    ScanCallbackCompat callbackCompat = callbackCompatRef.get();
    if (callbackCompat == null) return;
    List<ScanResultCompat> compatResults = new ArrayList<>(results.size());
    for (ScanResult result : results) {
        compatResults.add(new ScanResultCompat(result));
    }
    callbackCompat.onBatchScanResults(compatResults);
}
 
Example 42
Project: DailyStudy   File: BleActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 扫描结果的回调,每次扫描到一个设备,就调用一次。
 * @param callbackType
 * @param result
 */
@Override
public void onScanResult(int callbackType, ScanResult result) {
    //Log.d(Tag, "onScanResult");
    if(result != null){
        System.out.println("扫面到设备:" + result.getDevice().getName() + "  " + result.getDevice().getAddress());

        //此处,我们尝试连接MI 设备
        if (result.getDevice().getName() != null && mTargetDeviceName.equals(result.getDevice().getName())) {
            //扫描到我们想要的设备后,立即停止扫描
            result.getDevice().connectGatt(BleActivity.this, false, mGattCallback);
            mBluetoothLeScanner.stopScan(mScanCallback);
        }
    }
}
 
Example 43
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private ScanCallback initializeScanCallbackFor(final FlowableEmitter<SensorRecord> subscriber){
    return new ScanCallback() {
        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            subscriber.onNext(new BLEMeasurementsRecord(results));
        }
    };
}
 
Example 44
Project: UDOOBluLib-android   File: UdooBluAppCompatActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    if (result != null) {
        BluetoothDevice device = result.getDevice();
        if (device != null) {
            onBluDiscovered(result.getRssi(), device);
        }
    }
}
 
Example 45
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 5 votes vote down vote up
@Override
     public void onScanResult(int callbackType, final ScanResult result) {
         //Log.i(TAG, "Scan Result:"+result.toString()); 

 		int connType = 3;
int addrType = 0;

String strAddr=result.getDevice().getAddress();
byte[] addr = stringToAddress(strAddr);

         byte[] data = result.getScanRecord().getBytes();
         int rssi = result.getRssi();
         
         advReportNative(connType, addrType, addr, data, rssi);
     }
 
Example 46
Project: MagicLight-Controller   File: SelectDeviceActivity.java   Source Code and License 5 votes vote down vote up
private void processResult(final ScanResult result) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            String deviceName = result.getScanRecord().getDeviceName();
            if(deviceName != null && !deviceName.equals("") && !deviceList.contains(deviceName)) {
                mLeDeviceListAdapter.addDevice(result.getDevice());
                deviceList.add(deviceName);
            }
        }
    });
}
 
Example 47
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 5 votes vote down vote up
private void createNatives() {
    nativeCallback = new android.bluetooth.le.ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            int convertedType = LollipopUtils.convertNativeStatusToCompat(callbackType);
            com.taptrack.tcmptappy.blescannercompat.ScanResult convertedResult = LollipopUtils.convertNativeResultToCompat(result);

            compatCallback.onScanResult(convertedType,convertedResult);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            compatCallback.onBatchScanResults(LollipopUtils.convertNativeResultListToCompat(results));
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            compatCallback.onScanFailed(LollipopUtils.convertNativeScanFailedErrorCodeToCompat(errorCode));
        }
    };

    this.nativeFilters = LollipopUtils.convertCompatScanFilterListToNative(compatFilters);
    this.nativeSettings = LollipopUtils.convertCompatScanSettingsToNative(compatSettings);
}
 
Example 48
Project: ProjectPlutoAndroid   File: ScanActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_connect);
    ButterKnife.bind(this);

    mScanPresenter = new ScanPresenter(this, new BaseView(this));
    mAdapter = new ScanResultAdapter(this, new ArrayList<ScanResult>());
    mDeviceList.setAdapter(mAdapter);
}
 
Example 49
Project: ProjectPlutoAndroid   File: ScanActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Replaces the contents of the ui scanResult list with specified scanResults
 */
@Override
public void updateScanResults(final Collection<ScanResult> scanResults) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mAdapter.clear();
            mAdapter.addAll(scanResults);
            mAdapter.notifyDataSetChanged();
        }
    });
}
 
Example 50
Project: ProjectPlutoAndroid   File: BleScannerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testScanResult() {
    ArgumentCaptor<BleScanner.ScanResultEvent> event
            = ArgumentCaptor.forClass(BleScanner.ScanResultEvent.class);

    ScanResult result = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    when(result.getDevice()).thenReturn(device);
    when(device.getAddress()).thenReturn("EB:22:19:0E:B2:01");
    mScanner.mScanCallback.onScanResult(1, result);

    verify(mBus, times(1)).post(event.capture());
    assertEquals(event.getValue().addressToResult.get("EB:22:19:0E:B2:01"), result);
}
 
Example 51
Project: ProjectPlutoAndroid   File: ScanActivityTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUpdateScanResult() {
    List<ScanResult> results = new ArrayList<>();
    ScanResult result = mock(ScanResult.class);
    results.add(result);
    activity.updateScanResults(results);

    assertEquals(1, activity.mAdapter.getCount());
    assertEquals(result, activity.mAdapter.getItem(0));
}
 
Example 52
Project: ProjectPlutoAndroid   File: ScanPresenterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOnScanResult() {
    ScanResult result1 = mock(ScanResult.class);
    ScanResult result2 = mock(ScanResult.class);
    Map<String, ScanResult> resultMap = new HashMap<>();
    resultMap.put("address1", result1);
    resultMap.put("address2", result2);
    BleScanner.ScanResultEvent event = new BleScanner.ScanResultEvent(resultMap);
    presenter.onScanResult(event);

    verify(scanView, times(1)).updateScanResults(scanResultCaptor.capture());
    assertEquals(scanResultCaptor.getValue(), resultMap.values());
}
 
Example 53
Project: ProjectPlutoAndroid   File: ScanPresenterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConnect() {
    ScanResult result = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    doReturn(device).when(result).getDevice();
    presenter.mBtService = bluetoothService;
    presenter.onClickConnect(result);

    verify(bluetoothService, times(1)).connect(device, false);
    verify(baseView, times(1)).startActivity(ChangeColorActivity.class);
}
 
Example 54
Project: BleLib   File: BleService.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (mScanLeDeviceList.contains(result.getDevice())) return;
        mScanLeDeviceList.add(result.getDevice());
        if (mOnLeScanListener != null) {
            mOnLeScanListener.onLeScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
        }
        broadcastUpdate(ACTION_BLUETOOTH_DEVICE, result.getDevice());
        Log.i(TAG, "onScanResult: name: " + result.getDevice().getName() +
                ", address: " + result.getDevice().getAddress() +
                ", rssi: " + result.getRssi() + ", scanRecord: " + result.getScanRecord());
    }
}
 
Example 55
Project: BleLib   File: MultipleBleService.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (mScanLeDeviceList.contains(result.getDevice())) return;
        mScanLeDeviceList.add(result.getDevice());
        if (mOnLeScanListener != null) {
            mOnLeScanListener.onLeScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
        }
        broadcastUpdate(ACTION_BLUETOOTH_DEVICE, result.getDevice());
        Log.i(TAG, "onScanResult: name: " + result.getDevice().getName() +
                ", address: " + result.getDevice().getAddress() +
                ", rssi: " + result.getRssi() + ", scanRecord: " + result.getScanRecord());
    }
}
 
Example 56
Project: u2f-ble-test   File: U2FBLEDevice.java   Source Code and License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
	logger.debug("Device detected " + result.getDevice().getAddress() + " " + result.getDevice().getName());
	detectTimeout.cancel();
	bluetoothAdapter.getBluetoothLeScanner().stopScan(this);
	U2FBLEDevice device = new U2FBLEDevice(result.getDevice(), this.notification, this.logger, this.context);
	this.notification.onDeviceDetected(device);
}
 
Example 57
Project: xDrip   File: BluetoothGlucoseMeter.java   Source Code and License 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 58
Project: xDrip-plus   File: BluetoothGlucoseMeter.java   Source Code and License 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 59
Project: SensorLib   File: DsScanCallback.java   Source Code and License 5 votes vote down vote up
@Override
@CallSuper
public synchronized void onScanResult(int callbackType, ScanResult result) {
    // check if we already reported this device in this scan iteration
    if (mScannedAddresses.contains(result.getDevice().getAddress())) {
        //Log.d(TAG, "Skipping BLE device: already discovered.");
        return;
    }
    mScannedAddresses.add(result.getDevice().getAddress());

    Log.d(TAG, "New BLE device: " + result.getDevice().getName() + "@" + result.getRssi());
    SensorInfo s = new SensorInfo(result.getDevice().getName(), result.getDevice().getAddress());

    boolean ret;
    if (s.getDeviceClass() != null) {
        // call this method for the DsSensorPickerFragment,
        // because we need some information about the Bluetooth device
        ret = mSensorCallback.onKnownSensorFound(s, result.getRssi());
        // Logical OR because onKnownSensorFound(KnownSensor, BluetoothDevice)
        // always returns true. If we should stop scanning, then this method returns
        // false => ret == false.
        ret &= mSensorCallback.onKnownSensorFound(s);
    } else {
        ret = mSensorCallback.onUnknownSensorFound(result.getDevice().getName(), result.getDevice().getAddress());
    }

    if (!ret) {
        DsSensorManager.cancelRunningScans();
    }
}
 
Example 60
Project: Android-BLE-Library   File: BLEScanner.java   Source Code and License 5 votes vote down vote up
private void initScanData() {
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            Log.i(TAG, "onScanResult" + result);
            String address = result.getDevice().getAddress();
            String name;
            ScanRecord scanRecord = result.getScanRecord();
            name = scanRecord == null ? "unknown" : scanRecord.getDeviceName();
            scanResultListener.onResultReceived(name, address);
        }

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

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed");
            scanResultListener.onScanFailed(errorCode);
        }
    };
    filters = new ArrayList<>();
    filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE)).build());
    scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
}