android - 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 ...
解决方案
对于使用 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"));
推荐阅读
- javascript - Firefox 最新更新 - Javascript 问题
- mongodb - MongoDB 排序与文本搜索的分数以及其他标准弹簧数据
- python - 每周自动电子邮件
- ios - 通过点击按钮发送通知时,发生崩溃
- json - 从 JSON 数据中获取值
- java - RecyclerView 适配器高亮单击或当前项
- c++ - 模板专业化 Clang 10.0
- android - recyclerview 项目大小与布局中的大小不同
- java - 使用 Spring Security 时,Tomcat 访问日志中缺少用户 (%u)
- java - 如何使 BoxLayout 正确左对齐?