java - 在配对或连接蓝牙扫描仪(Inateck)和移动设备时,活动被破坏
问题描述
我正在设置蓝牙扫描仪 Android 应用程序,我正在尝试使用 android 代码连接蓝牙扫描仪 (Inateck) 和移动设备。
我的要求:通过我的应用程序将两个设备配对。与设备连接。蓝牙扫描仪将扫描条形码中的代码,我需要将其显示在我的应用程序编辑文本中。
首先,我将使用 Android 蓝牙 API 发现蓝牙设备。
public final BroadcastReceiver AvailableBlueToothDevicesBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (availableDevice == null) {
availableDevice = new MutableLiveData<BluetoothDevice>();
}
availableDevice.setValue(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
if (availableDevice == null) {
availableDevice = new MutableLiveData<BluetoothDevice>();
}
availableDevice.setValue(null);
}
}
};
这是用于获取可用设备的广播接收器。
我会注册这个
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getContext().registerReceiver(broadcastManager.AvailableBlueToothDevicesBroadcastReceiver, discoverDevicesIntent);
有了这个,我将获得附近的蓝牙设备列表。我将在 Recyclerview 中列出。在单击任何这些设备时,必须执行设备之间的配对。所以为此我使用了下面的代码。
private void pairDevice(BluetoothDevice bluetoothDevice){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
Log.d(TAG, "Trying to pair with " +
bluetoothDevicebluetoothDevice.getName());
bluetoothDevice.createBond();
}
}
执行此代码后,将出现一个对话框,要求与设备配对。一旦配对完成,我的 Activity 的 onDestroy() 生命周期事件就会被调用,并且默认情况下会重新创建我的 Activity。这会丢失我之前在活动中的数据。这不应该发生。但配对就是成功。
当我尝试连接我的 Android 手机和蓝牙扫描仪设备时会发生这种情况。但是,如果我尝试在两部安卓手机之间配对,则不会发生调用 onDestroy() 事件。谁能告诉我为什么会这样?
解决方案
某些设备配置可能会在运行时更改(例如屏幕方向、键盘可用性以及用户启用多窗口模式时)。当发生这种变化时,Android 会重新启动正在运行的 Activity(调用 onDestroy(),然后调用 onCreate())。重新启动行为旨在通过使用与新设备配置匹配的替代资源自动重新加载您的应用程序来帮助您的应用程序适应新配置。
在我的情况下,我试图连接到将充当物理键盘的蓝牙扫描仪。所以我们需要在AndroidManifest.xml的activity中添加configChanges
android:configChanges="方向|screenSize|键盘|keyboardHidden|导航"
但是方向和屏幕大小在配置更改中不是必须的。但其他人是。
更多信息请参考: https ://developer.android.com/guide/topics/resources/runtime-changes
推荐阅读
- excel - 使用 VB 脚本获取 Excel 工作表名称并重命名
- angular - 如何在 Angular Timepicker 中设置默认值?
- c# - 如何解决此错误 stale element reference: element is not attach to the page document
- javascript - 如何删除 indicatorContainer(IndicatorsContainer 的第一个子项)的填充?
- google-bigquery - 将数据插入调整到 BigQuery
- python - 如何通过 pandas 读取 csv 作为其原始状态 [如不更改其格式]
- assembly - 将 x86 四元数组装到欧拉角输出错误的顺序
- html - 展开容器而不展开父/整行
- javascript - 在检查唯一值时使用 {} 或使用 new Set() 声明一个空对象更好吗?
- ios - 使用 react-native-community/voice 的语音到文本在 iOS 中没有给出正确的结果