首页 > 解决方案 > Getting UUID of nearby beacon

问题描述

I have an application that i want to scan nearby beacons and get their RSSI , UUID , major and minor. to test my code i used to make a virtual beacon using Beacon Simulator app on another device. I checked several ways but none of them worked fine:

1) in this code i made a scanner class and starting scan in my fragment and get address(I think it is mac address of BLE device) and RSSI but when i want to get UUID it says that it is null

private val mLeScanCallback = BluetoothAdapter.LeScanCallback { device, rssi, scanRecord ->
    if (rssi > signalStrength) {
        mHandler.post{
            val uuid : String
            if(device.uuids != null){
                uuid = device.uuids[0].uuid.toString()
            }
            else{
                uuid = "nullll"
                scanRecord
            }
            Log.i("scan" , "device founded -> address:" + device.address + " name: " + device.name +" uuid: " + uuid + " RSSI: " + rssi + " type: " + device.type)
        }
    }
}

and call this function in my fragment to do the scan:

private fun scanLeDevice(enable: Boolean) {
    if (enable && !isScanning) {
        Log.i("scan" , "starting scan ...")

        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed({
            Log.i("scan" , "stopping scan ...")

            isScanning = false
            mBluetoothAdapter.stopLeScan(mLeScanCallback)

            stopScan()
        }, scanPeriod)

        isScanning = true
        mBluetoothAdapter.startLeScan(mLeScanCallback)
    } else {
        isScanning = false
        mBluetoothAdapter.stopLeScan(mLeScanCallback)
    }
}

2)second way i checked was to use this function in my fragment but nothing happened and no beacon was detected:

private val beaconManager = BeaconManager.getInstanceForApplication(MainApplication.applicationContext())



override fun onBeaconServiceConnect() {
    beaconManager.removeAllRangeNotifiers()
    beaconManager.addRangeNotifier(object : RangeNotifier {
        override fun didRangeBeaconsInRegion(beacons: Collection<Beacon>, region: Region) {
            if (beacons.size > 0) {
                Log.i(TAG, "The first beacon I see is about " + beacons.iterator().next().getDistance() + " meters away.")
            }
        }
    })

    try {
        beaconManager.startRangingBeaconsInRegion(Region("myRangingUniqueId", null, null, null))
    } catch (e: RemoteException) {
    }

}

I really dont know what is wrong ...

标签: androidkotlinbluetooth-lowenergybeaconaltbeacon

解决方案


对于使用 Android Beacon 库的第二个清单,问题是您永远不会调用beaconManager.bind(this),因此,您永远不会得到回调,onBeaconServiceConnect并且该方法内的任何代码都不会执行。

由于您使用的是 Fragment 而不是 Activity,因此请注意实际实现的所有方法BeaconConsumer,具有该onBeaconServiceConnect方法的类必须实现这些方法。有关该链接的更多信息,请参见此处

最后,如果您正在寻找 iBeacon 发射器,您必须设置信标布局。执行此操作的 java 代码是beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));


推荐阅读