gpt4 book ai didi

java - 线程和事件

转载 作者:行者123 更新时间:2023-12-01 04:41:06 24 4
gpt4 key购买 nike

我真的被困在这里了,我已经阅读了很多有关 Android 线程的文章,但我无法找到适合我的项目的答案。

我有一个前端(管理 GUI)和一个后端(管理数据和内容)。我需要在后端完成运行线程后立即更新 GUI,但我不知道如何更新!

Main.java 包前端

public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread thread = new Thread() {
@Override
public void run() {
Server server = new Server(getApplicationContext());
}

};
thread.start();

Server.java 包后端

public static List<String> lista = new ArrayList<String>();
public Server(Context context) {
Revisar archivo = New Revisar();
archivo.DoSomething();
}

archivo.doSomething 完成后,我需要使用存储在静态列表中的后端数据更新 GUI。

有什么建议吗?

最佳答案

正如您所猜测的,您无法从后台线程更新 GUI。

通常,要执行您想要的操作,您可以使用消息处理机制将消息传递到 GUI 线程。通常,您传递 Runnable它将在 GUI 线程中执行。您还可以传递 Message如果您已对 Handler 进行子类化并添加了处理消息的代码。

消息被传递给处理程序。您可以在 GUI 线程中创建自己的处理程序,也可以使用已存在的多个处理程序之一。例如,每个 View 对象都包含一个 Handler。

或者您可以简单地使用 runOnUiThread () Activity 方法。

模式 1,处理程序加可运行对象:

// Main thread
private Handler handler = new Handler();

...

// Some other thread
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "this is being run in the main thread");
}
});

模式 2,处理程序加消息:

// Main thread
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "dealing with message: " + msg.what);
}
};

...

// Some other thread
Message msg = handler.obtainMessage(what);
handler.sendMessage(msg);

模式3,调用runOnUiThread():

// Some other thread
runOnUiThread(new Runnable() { // Only available in Activity
public void run() {
// perform action in ui thread
}
});

模式 4,将 Runnable 传递给 View 的内置处理程序:

// Some other thread
myView.post(new Runnable() {
public void run() {
// perform action in ui thread, presumably involving this view
}
});

关于java - 线程和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16532913/

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