我想在 AsyncTask
的 doInBackground()
中做一些工作时询问用户一些细节(在 UI 线程中向用户显示一些带有选择的对话框),以及用户选择后,使用对话框中选择的参数在 doInBackground()
中继续工作。
将此参数传输到 doInBackground()
的最佳机制是什么?我应该如何暂停(并继续)线程执行 doInBackground()
(也许是 object.wait()
和 notify()
?)?为此,我应该使用 Handler
吗?
最佳答案
我会在实际开始后台任务之前要求用户输入。如果这不可能,则有几种可能性:
您可以使用锁定对象并在其上执行通常的 wait()/notify() 操作。不过,您仍然需要将数据从 UI 线程传递到后台线程
我会使用队列将数据从 UI 线程传递到后台线程,并让它处理所有锁定。
类似这样的东西(一种伪代码)
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
关于android - 如何暂停 AsyncTask 以询问用户的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636927/