首页 > 解决方案 > 在配对或连接蓝牙扫描仪(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() 事件。谁能告诉我为什么会这样?

标签: javaandroidandroid-bluetooth

解决方案


某些设备配置可能会在运行时更改(例如屏幕方向、键盘可用性以及用户启用多窗口模式时)。当发生这种变化时,Android 会重新启动正在运行的 Activity(调用 onDestroy(),然后调用 onCreate())。重新启动行为旨在通过使用与新设备配置匹配的替代资源自动重新加载您的应用程序来帮助您的应用程序适应新配置。

在我的情况下,我试图连接到将充当物理键盘的蓝牙扫描仪。所以我们需要在AndroidManifest.xml的activity中添加configChanges

android:configChanges="方向|screenSize|键盘|keyboardHidden|导航"

但是方向和屏幕大小在配置更改中不是必须的。但其他人是。

更多信息请参考: https ://developer.android.com/guide/topics/resources/runtime-changes


推荐阅读