为什么 BluetoothSocket.connect() 在 Toast.makeText().show() 之前调用?
Why is BluetoothSocket.connect() called before Toast.makeText().show()?
我试图在尝试连接到我从 ListView 选择的 Bluetooth
设备之前显示 Toast 消息,但问题是 Toast
消息出现在connecting 以便用户可以知道他们的设备当前是否正在尝试连接到选定的 BT 设备。应该是这样的:
- 从
ListView
中选择的设备
- 吐司留言:"Connecting..."
btSocket.connect()
已调用并成功连接
- 吐司留言:"Connected!"
相反,它是这样发生的:
- 从
ListView
中选择的设备
btSocket.connect()
已调用并成功连接
- 吐司留言:"Connected!"
- 吐司留言:"Connecting..."
请注意,应用程序在尝试连接到 btSocket
时冻结,然后解冻并继续其工作。
示例代码:
listView_myDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothSocket btSocket;
// ... Determine which device is selected, etc.
Toast.makeText(MyActivity.this, "Connecting...", Toast.LENGTH_SHORT).show();
btSocket.connect();
Toast.makeText(MyActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
// ...
}
});
问题是连接可能需要一点时间,您必须确保 Toast-CONNECTED 仅在连接后触发。最快但不是最好的解决方案是
BluetoothSocket btSocket;
Toast.makeText(MyActivity.this, "Connecting...", Toast.LENGTH_SHORT).show();
btSocket.connect();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (btSocket.isConnected()){
Toast.makeText(MyActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
} }
}, 5000);
所以你给连接时间,5秒后检查
我试图在尝试连接到我从 ListView 选择的 Bluetooth
设备之前显示 Toast 消息,但问题是 Toast
消息出现在connecting 以便用户可以知道他们的设备当前是否正在尝试连接到选定的 BT 设备。应该是这样的:
- 从
ListView
中选择的设备
- 吐司留言:"Connecting..."
btSocket.connect()
已调用并成功连接- 吐司留言:"Connected!"
相反,它是这样发生的:
- 从
ListView
中选择的设备
btSocket.connect()
已调用并成功连接- 吐司留言:"Connected!"
- 吐司留言:"Connecting..."
请注意,应用程序在尝试连接到 btSocket
时冻结,然后解冻并继续其工作。
示例代码:
listView_myDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothSocket btSocket;
// ... Determine which device is selected, etc.
Toast.makeText(MyActivity.this, "Connecting...", Toast.LENGTH_SHORT).show();
btSocket.connect();
Toast.makeText(MyActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
// ...
}
});
问题是连接可能需要一点时间,您必须确保 Toast-CONNECTED 仅在连接后触发。最快但不是最好的解决方案是
BluetoothSocket btSocket;
Toast.makeText(MyActivity.this, "Connecting...", Toast.LENGTH_SHORT).show();
btSocket.connect();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (btSocket.isConnected()){
Toast.makeText(MyActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
} }
}, 5000);
所以你给连接时间,5秒后检查