How to scan for available bluetooth devices in range in android?

后端 未结 3 1630
南旧
南旧 2020-12-08 08:05

I need to get a list of available bluetooth devices in the area using google android 2.1.

Thing is, i don\'t just need a list of those devices, i need some unique id

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 09:04

    This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.

    Make sure you import BeaconManager

    private BeaconManager beaconManager;
    
    //In onCreate method
    beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.getBeaconParsers().add(new BeaconParser().
                    setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    
    //use these out of the onCreate method
    public void onScanStart(View view) {
            stopScanButton.setEnabled(true);
            scanningButton.setEnabled(false);
            beaconManager.bind(this);
    }
    
    @Override
    public void onBeaconServiceConnect() {
        beaconManager.removeAllRangeNotifiers();
        beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection beacons, Region region) {
        for (Beacon b : beacons) {
            System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi()));
      });
        try {
    //Tells the BeaconService to start looking for beacons that match the passed.
            beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
        } catch (RemoteException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        }
    }
    

    Let me know if that works for you!

提交回复
热议问题