gpt4 book ai didi

java - 等待接收数据而不阻塞ui线程蓝牙android

转载 作者:行者123 更新时间:2023-12-02 01:26:03 25 4
gpt4 key购买 nike

我是 Android 编程新手,正在编写一个使用蓝牙的回合制游戏的简单应用程序。我的应用程序由 Main Activity 和 SecondActivity 组成,Main Activity 负责启动蓝牙连接并交换一些配置消息,而 SecondActivity 则通过游戏 map 实现自定义 View 。即使在自定义 View 中,我也可以正确配对设备并在两者之间交换信息,问题是在自定义 View 中我会等待接收信息而不阻塞 ui 线程,目前我正在以这种方式等待接收数据

自定义 View

state = bluetoothService.getState();
while(state != NOT_EMPTY){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = bluetoothService.getState();
}
info = bluetoothService.getMessage();

这显然会导致黑屏和无响应,是否有其他方法等待接收数据?

连接是通过 BluetoothService 类通过线程进行管理的,负责读取数据的线程负责执行此操作

private class ConnectedThread extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
private final OutputStream mOutStream;

public ConnectedThread(BluetoothSocket socket) {
mSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

try {
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}

mInStream = tmpIn;
mOutStream = tmpOut;
}

public void run(){
byte[] buffer = new byte[1024];

int bytes; // bytes returned from read()

// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mInStream.read(buffer);
if(bytes != 0) {
String incomingMessage = new String(buffer, 0, bytes);
message = incomingMessage;
mState = NOT_EMPTY;
}
} catch (IOException e) {
break;
}
}
}
}

//getMessage method just returns message if not null

最佳答案

主要思想不是从 Activity 中拉取,而是从后台线程调用 Activity 的方法。

因此,在构造读取器线程时,传递对 Activity 的引用并创建一个处理程序:

    private SecondActivity mActivity;
private Handler mActivityHandler;

public ConnectedThread(BluetoothSocket socket, SecondActivity activity) {
mActivity = activity;
mActivityHandler = new Handler(activity.getMainLooper());

...
}

收到消息后,调用 Activity 的方法。该调用必须在主线程上完成,因此使用处理程序:

final String message = incomingMessage;
Runnable runnable = new Runnable() {
@Override
public void run() {
mActivity.onMessageReceived(message);
}
};
mActivityHandler.post(myRunnable);

在 Activity 中,对消息执行一些操作:

public void onMessageReceived(String message) {
// handle the message...
}

关于java - 等待接收数据而不阻塞ui线程蓝牙android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com