2

我正在尝试获取 android 中可破坏的蓝牙设备的列表。我可以获取设备并使用 ArrayAdapter,填充设备的 ListView。我的问题是,如何将它们保存到列表中,以便可以将此信息用于其他功能?我试过在 android 开发者网站上查找,它所拥有的只是 ListView 的教程。我还寻找其他教程或解释,似乎得到了错误的信息。

我的代码是:

protected List<String> doInBackground(Void... arg0) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();

// Create a BroadcastReceiver for ACTION_FOUND
final List<String> discoverableDevicesList = new ArrayList<String>();

final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
            // Add the name and address to an array adapter to show in a ListView
            System.out.println(device.getName());
            discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);   
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

return discoverableDevicesList;

}

这可能与扫描蓝牙设备相关的发现时间有关,但我认为发现每个设备后我都可以将其添加到列表中?有没有人遇到过类似的事情或有可能的解决方案?非常感激!

4

1 回答 1

1

看起来它可能与 UI 线程有关。您是否尝试触发 AsyncTask 以在蓝牙设备发现时填充 ListView?我看到你这样做:

           // Add the name and address to an array adapter to show in a ListView
        System.out.println(device.getName());
        discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);   

在 Receiver 内部,但无法保证 UI 线程已准备好处理响应。

我从http://android-developers.blogspot.com/2009/05/painless-threading.html得到这个

于 2013-02-27T19:41:43.237 回答