Android 无法在textView中显示蓝牙设备
我希望在扫描过程中发现设备名称时,设备名称会显示在我应用程序的文本视图中,但不会显示任何内容Android 无法在textView中显示蓝牙设备,android,bluetooth,Android,Bluetooth,我希望在扫描过程中发现设备名称时,设备名称会显示在我应用程序的文本视图中,但不会显示任何内容 bluetoothAdapter = (BluetoothAdapter.getDefaultAdapter()); bluetoothAdapter.enable(); bluetoothAdapter.startDiscovery(); BroadcastReceiver mReceiver = new BroadcastReceiver() { public
bluetoothAdapter = (BluetoothAdapter.getDefaultAdapter());
bluetoothAdapter.enable();
bluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
textView.append(device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
我看到蓝牙已成功启用,我的其他设备可见,但从未显示任何内容
bluetoothAdapter = (BluetoothAdapter.getDefaultAdapter());
bluetoothAdapter.enable();
bluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
textView.append(device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
我知道上面的代码是为了在listView中使用,但它在textView中是否仍然有效?我想我已经在这里找到了问题所在 调用bluetoothAdapter.startDiscovery()时出现问题;就在bluetoothAdapter.enable()之后 适配器显然需要几秒钟的时间来完成所有设置,然后才能开始使用它 所以我在这两者之间加了一点延迟:
bluetoothAdapter.enable();
try {
Thread.sleep(3000);//3 seconds
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
bluetoothAdapter.startDiscovery();
现在一切似乎都正常了。如果刚好在
textView.append(device.getAddress())这一行的上方代码>放置一个Toast,例如Toast.makeText(getContext(),device.getAddress(),Toast.LENGTH_SHORT).show()
并告诉我们如果Toast出现了怎么办?什么都没有显示,就像该方法从未被使用过一样。这意味着你的应用程序找不到你的BT设备,这与textView无关。但它一定找到了它,因为它通过“bluetoothAdapter.enable()”打开了蓝牙我的意思是,运行应用程序的设备无法发现任何其他支持蓝牙的设备。它从不进入if语句。尝试在那里调试代码,看看会发生什么。