Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/191.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android蓝牙可发现性和意图_Android_Android Intent_Bluetooth - Fatal编程技术网

Android蓝牙可发现性和意图

Android蓝牙可发现性和意图,android,android-intent,bluetooth,Android,Android Intent,Bluetooth,据我所知,“表现良好”的Android应用程序将在onPause()中注销其广播接收器。但是,当您启用蓝牙可发现性时,这会很复杂 假设我的行为良好的活动在其onPause()中注销其蓝牙\u扫描\u模式\u更改的接收器。然后,用户点击应用程序中的按钮以启用可发现性,并运行以下代码: Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivity(discover

据我所知,“表现良好”的Android应用程序将在onPause()中注销其广播接收器。但是,当您启用蓝牙可发现性时,这会很复杂

假设我的行为良好的活动在其onPause()中注销其蓝牙\u扫描\u模式\u更改的接收器。然后,用户点击应用程序中的按钮以启用可发现性,并运行以下代码:

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(discoverableIntent);
到目前为止,在我遇到的所有情况下,广播意图都是在调用我的活动的onResume()方法之前激发的,这意味着它是在我的活动重新注册其接收器之前激发的,并且该活动没有接收到蓝牙被发现的广播意图

我的解决方法是只保留广播意图,即不在onPause()中注销它


我的问题是:有更好的解决办法吗?让广播接收器在onPause()和onResume()之间注册,这真的不好吗?谢谢

您可以将蓝牙交互委托给服务。服务可以注册/注销BroadcastReceiver,该服务贯穿活动的生命周期。处于服务的同一进程中,活动可以在恢复后立即连接到它,并获得BroadcastReceiver接收到的任何信息。

您可以在onResume()中获得当前的蓝牙可发现状态,如下所示:

final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
boolean discoverable = adapter.getScanMode() == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
这样,您就可以继续在onPause()中注销广播接收器,并在onResume()中重新注册它