Solution for BLE scan's SCAN_FAILED_APPLICATION_REGISTRATION_FAILED?

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

My Android app scans BLE devices, and from a certain point it start to fails with error code 2 (ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED). I'm using Nexus 9, 5.0.1 Lollipop.

This problem continued even after I relaunched the app, and when I restarted the Bluetooth service from Settings, I could finally get rid of the problem. But this problem is recurring, and I think I'm coding in a wrong way; BLE related APIs are new and there is few information.

Does anyone know a general solution for this error, preferably not requiring restart of the Bluetooth service? Even though this error code is documented in Android API reference, I don't know how to handle it properly.

回答1:

You should perform operations only success initialization of BT adapter. To be sure that it is ready create intent filter:

val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED) 

and broadcast receiver(you will perform action only if adapter is ready):

val broadcastReceiver = object: BroadcastReceiver() {             override fun onReceive(context: Context, intent: Intent?) {                 val action = intent?.action                 if (action != null && action == BluetoothAdapter.ACTION_STATE_CHANGED) {                     val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)                     when (state) {                         BluetoothAdapter.STATE_ON -> {                             if (bluetoothAdapter.isEnabled) {                                //perform your task here                             }                         }                         BluetoothAdapter.STATE_OFF -> {}                     }                 }             }         } 

then register receiver:

registerReceiver(broadcastReceiver, filter) 

and relaunch adapter(this part can be replaces with check):

bluetoothAdapter.disable() bluetoothAdapter.enable() 

DONE!



回答2:

When you got the error

SCAN_FAILED_APPLICATION_REGISTRATION_FAILED 

You should disable the BluetoothAdapter

BluetoothAdapter.getDefaultAdapter().disable(); 

Disabling BluetoothAdapter, the event STATE_TURNING_OFF is fired. Once this event is fired, try to reconnect to the 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; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!