Shi*_*llo 16 bluetooth-lowenergy android-bluetooth android-5.0-lollipop
我的Android应用程序扫描BLE设备,从某一点开始,它开始失败,错误代码为2(ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED).我正在使用Nexus 9,5.0.1 Lollipop.
即使在我重新启动应用程序后,这个问题仍然存在,当我从"设置"重新启动蓝牙服务时,我终于可以摆脱这个问题了.但是这个问题反复发生,我认为我编码错误; BLE相关的API是新的,信息很少.
有没有人知道这个错误的一般解决方案,最好不要求重启蓝牙服务?即使Android API参考中记录了此错误代码,我也不知道如何正确处理它.
当你得到错误
SCAN_FAILED_APPLICATION_REGISTRATION_FAILED
Run Code Online (Sandbox Code Playgroud)
您应该禁用BluetoothAdapter
BluetoothAdapter.getDefaultAdapter().disable();
Run Code Online (Sandbox Code Playgroud)
禁用BluetoothAdapter会触发事件STATE_TURNING_OFF。触发此事件后,尝试重新连接到BluetoothAdapter:
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "bluetooth adapter turned off");
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "bluetooth adapter try to enable");
BluetoothAdapter.getDefaultAdapter().enable();
}}, 500);
break;
Run Code Online (Sandbox Code Playgroud)
事实证明,蓝牙 LE 需要 AndroidManifest.xml 中的以下 Android 应用程序权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--BLE scanning is commonly used to determine a user's location with Bluetooth LE beacons. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- if your app targets API level 21 or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
<!--app is available to BLE-capable devices only. -->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Run Code Online (Sandbox Code Playgroud)
除了主要活动:
// onResume()
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_ENABLE_CODE);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4556 次 |
| 最近记录: |