问题描述
我想在AsyncTask
的doInBackground()
中做一些工作时向用户询问一些细节(向用户显示UI线程中具有选择的对话框),并在用户选择后继续在doInBackground()
中执行所选择的工作对话框中的参数.
I want to ask user for some details while doing some work in doInBackground()
of AsyncTask
(showing to user some dialog with choices in UI-thread), and after users choice continue the job in doInBackground()
with chosen parameters from dialog.
将此参数传输到doInBackground()
的最佳机制是什么?我应该如何暂停(并继续)执行doInBackground()
的线程(也许是object.wait()
和notify()
?)?为此,我应该使用Handler
吗?
What is a best mechanism of transfer this parameter to doInBackground()
? How I should pause (and continue) thread doing doInBackground()
(maybe object.wait()
and notify()
?)? Should I use a Handler
for this purpose?
推荐答案
在实际启动后台任务之前,我会先询问用户输入.如果这不可能,则有以下几种可能性:
I would ask user for input before actually starting background task. If this is not possible there are couple possibilities:
-
您可以使用锁对象并对其执行通常的wait()/notify()事情.不过,您仍然需要将数据从UI线程传递到后台线程
You can use lock object and do usual wait()/notify() stuff on it. You still need to pass data from UI thread to your background thread though
我将使用队列将数据从UI线程传递到后台线程,并让它处理所有锁定.
I would use queue to pass data from UI thread to background thread and let it handle all the locking.
类似这样的东西(伪代码)
Something like this (kind of pseudo-code)
class BackgroundTask extends AsyncTask<BlockingQueue<String>, ...> {
void doInBackground(BlockingQueue<String> queue) {
...
String userInput = queue.take(); // will block if queue is empty
...
}
}
// Somewhere on UI thread:
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
BackgroundTask task = new BackgroundTask<BlockingQueue<String>,....>();
task.execute(queue);
....
....
String userInput = edit.getText().toString(); // reading user input
queue.put(userInput); // sending it to background thread. If thread is blocked it will continue execution
这篇关于如何暂停AsyncTask询问用户详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!