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   View source code 8 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   View source code 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: ITagAntiLost   File: NewDevicePresenter.java   View source code 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 4
Project: miband-android   File: MiBand.java   View source code 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 5
Project: AndroidSDK2.0   File: DeviceListActivity.java   View source code 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 6
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   View source code 6 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 7
Project: plen-Scenography_Android   File: PlenConnectionActivityPresenter.java   View source code 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 8
Project: react-native-ble-manager   File: LollipopScanManager.java   View source code 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 9
Project: ProjectPlutoAndroid   File: ScanActivity.java   View source code 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 10
Project: ProjectPlutoAndroid   File: BleScannerTest.java   View source code 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 11
Project: ProjectPlutoAndroid   File: ScanActivityTest.java   View source code 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 12
Project: u2f-ble-test   File: MainActivity.java   View source code 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 13
Project: BLE-Mesh   File: BLEGattClients.java   View source code 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 14
Project: FastBle   File: BleManager.java   View source code 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 15
Project: miband-android   File: MiBand.java   View source code 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 16
Project: miband-android   File: ScanActivity.java   View source code 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 17
Project: UdooWtf   File: MainActivity.java   View source code 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 18
Project: BluetoothCompat   File: ScanResultCompat.java   View source code 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 19
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   View source code 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 20
Project: Freeweight   File: BluetoothAndroid.java   View source code 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 21
Project: eddystone-android   File: Beacon.java   View source code 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 22
Project: SuperPanel   File: Ble.java   View source code 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 23
Project: myo-emg-visualizer   File: MyoListFragment.java   View source code 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 24
Project: proximity-manager   File: BeaconRegisterActivity.java   View source code 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 25
Project: PhoneProfilesPlus   File: BluetoothLEScanCallback21.java   View source code 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 26
Project: android-ble   File: BleScannerL.java   View source code 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 27
Project: android-ble   File: BTLEScannerOld.java   View source code 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 28
Project: android-ble   File: BTLEScannerOld.java   View source code 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 29
Project: react-native-ble   File: RNBLEModule.java   View source code 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 30
Project: android-beacon-library   File: ScanJobScheduler.java   View source code 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 31
Project: mDL-ILP   File: BTConnection.java   View source code 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 32
Project: android-ponewheel   File: BluetoothUtilImpl.java   View source code 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 33
Project: AndroidSDK2.0   File: DeviceListActivity.java   View source code 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 34
Project: KB_1711   File: MainActivity.java   View source code 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 35
Project: KB_1711   File: MainActivity.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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));
    }
}