gpt4 book ai didi

乱序多线程处理和对话框的Android问题

转载 作者:行者123 更新时间:2023-11-30 04:27:11 25 4
gpt4 key购买 nike

我似乎在计时线程和对话窗口方面一直存在问题。我试过使用线程、onCreate/onPrepare 或 AsyncTask 在后台进行一些下载/处理。通常情况下,当后台处理完成并关闭对话框窗口时,控制似乎返回到根线程(Activity/UI 线程?)对话框消失或类似 onPostExecute 的过程是完毕。这让我觉得我做错了。这是一个典型的结构(伪代码):

public class X {
protected String result = null;
protected ProgressDialog progressDialog;

public void onCreate() {
...
new XTask().execute();
progressDialog.show();
// result is null here, should be "hi"?

// do things with result, like barf on a NPE...sigh
}

private class XTask extends AsyncTask {
protected doInBackground() {
// Get URL.
// Look at contents, takes a few seconds.
// Return the result (should get sent to onPostExecute).
}
protected onPostExecute(r) {
result = r;
progressDialog.dismiss();
}
}
}

我认为,在 doPostExecute 设置结果并关闭对话框之后,处理然后在 onCreate 方法中继续。但是,此时在 onCreate 中,结果通常(不总是)为 null。有一个更好的方法吗?这仅仅是因为模拟器的普遍问题吗?

谢谢。

编辑:更具体地说,我的任务(在 doInBackground 中)获取一个 URL 并对响应进行一些处理。此过程需要 1-3 秒。然后,理论上,onPostExecute 将 X.result 设置为获取的内容。我知道 URL 内容有效且响应良好(不为空)。问题在于,在那 1-3 秒内,控件返回到 onCreate,就好像 progressDialog 根本就没有存在过(它根本没有显示在模拟器中,但我想这是正常的)。

我原以为调用 dialog.show() 是一种阻塞方法,即对话框出现,该方法直到消失才会继续,但似乎并非如此。我的 progressDialog.dismiss() 在设置 X.result 之前 被调用,或者根本没有被调用,或者 dismiss() 发生得更快/在分配之前,或者完全是其他原因出问题了...

改变 execute 和 progressDialog 的顺序无济于事,将其移至 onPreExecute() 也无济于事。奇怪的是,在我返回 onCreate 之前,onPostExecute 不会被调用。如果我在执行后有一个 Thread.sleep 循环(我认为给它时间会有所帮助),它永远不会完成任务,直到该循环完成并且我返回。例如:

new XTask().execute();
int z=0;
while (response == null && z < 50) {
Thread.sleep(500);
z++;
}
if (response == null) return;

任务的 onPostExecute 方法在“返回”之前不会被调用。嗯...也许在 onCreate 中影响了它。

最佳答案

ProgressDialog 通常用于在加载或繁重的处理过程中阻止用户交互,但主 UI 线程将继续执行。

如果您希望对结果执行某些操作,您必须在 XTask 的 onPostExecute 中或在 doInBackground 中获得结果后执行此操作。

private class XTask extends AsyncTask {

@Override
protected void onProgressUpdate(/*params*/){
//modify UI
}
protected doInBackground() {
// Get URL.
// Look at contents, takes a few seconds.

//Option A: Now have the result, do some other processing here
//Cant modify UI components from here, If you need to modify a UI component from
//here call publishProgress() and modify the component in onProgressUpdate()

// Return the result (should get sent to onPostExecute).
}
protected onPostExecute(r) {

result = r;
//Option B do some processing on the result
//You can modify UI components from here
progressDialog.dismiss();
}

关于乱序多线程处理和对话框的Android问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8280609/

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