android - Android ble扫描蓝牙附近的设备kotlin
问题描述
我正在尝试使用 BLE API 扫描附近的蓝牙设备,但它似乎无法正常工作
我已经在清单中添加了权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
以下在 oncreate 创建对象
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter = bluetoothManager.adapter
val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
when (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
else -> requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
}
创建扫描器回调对象并进一步扫描
private val leScanCallback = object :ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
Log.e("DeviceListActivity","onScanResult: ${result.device.address} - ${result.device.name}")
Log.e("device ", "kskd " + result.getRssi())
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
super.onBatchScanResults(results)
Log.e("DeviceListActivity","onBatchScanResults:${results.toString()}")
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Log.e("DeviceListActivity", "onScanFailed: $errorCode")
}
}
bluetoothLeScanner.startScan(leScanCallback)
在 logcat 中,我只看到以下内容
D/BluetoothAdapter: STATE_ON
D/BluetoothAdapter: BLE support array set: 010011
D/BluetoothLeScanner: Start Scan with callback
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=4 mScannerId=0
这是我的应用程序构建 gradle
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.mine.ble"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
有人可以指出我在这里可能缺少什么吗?
解决方案
试试这个代码
if (bluetooth.isEnabled()&&checkCoarseLocationPermission()){
final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
BluetoothDevice deviceExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d("TAG",deviceExtra.getName());
}
};
IntentFilter filter = new IntentFilter();
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver,filter);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGpsEnabled) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 12);
return;
}
adapter.cancelDiscovery();
adapter.startDiscovery();
}
清单.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
推荐阅读
- javascript - 如何在我的网站上以视频为背景绘制字母形状?
- javascript - 如何分别发布/安装开发和生产环境的 npm 包
- php - 奇怪的 PHP 会话变量和缓存问题从今天 2020 年 8 月 14 日开始
- apache-camel - 使用 Apache Camel,将 XMLGregorianCalendar 转换为 ZonedDateTime
- c# - 如何将 html 表情符号转换为文本?
- c# - C# httpwebrequest 调用将 SendFailure 返回到 URL,但 Postman 应用程序中的相同 URL 调用工作正常,并且在另一台服务器上工作正常
- objective-c - 内存泄漏 NSInvocationOperation
- postgresql - PostgreSQL 服务器用户管理员角色,用于批准从较低角色管理员对 db 的更改
- java - Spring-Boot WebMvcTest:如何使用 Authentication 对象参数测试控制器方法?
- scala - Scala:根据预定义数组 Spark 1.6 中存在的列值过滤 DF 行