android - 如何暂停 AsyncTask 以询问用户的详细信息?

标签 android android-asynctask

我想在 AsyncTaskdoInBackground() 中做一些工作时询问用户一些细节(在 UI 线程中向用户显示一些带有选择的对话框),以及用户选择后,使用对话框中选择的参数在 doInBackground() 中继续工作。

将此参数传输到 doInBackground() 的最佳机制是什么?我应该如何暂停(并继续)线程执行 doInBackground()(也许是 object.wait()notify()?)?为此,我应该使用 Handler 吗?

最佳答案

我会在实际开始后台任务之前要求用户输入。如果这不可能,则有几种可能性:

  1. 您可以使用锁定对象并在其上执行通常的 wait()/notify() 操作。不过,您仍然需要将数据从 UI 线程传递到后台线程

  2. 我会使用队列将数据从 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/

相关文章:

android - 西类牙语预选赛

Android 单选按钮背景与默认圆圈重叠

android-asynctask - asynctask #2 执行 doinbackground() 时发生错误

安卓 : Loading an image from the Web with Asynctask

java.lang.IllegalArgumentException : 'value' is not a valid managed object with realm 异常

c# - 无法从xamarin android调用firebase云函数

android - AOSCompiler出现错误-CM10-Galaxy Nexus/maguro

java - 我可以按顺序链接异步任务吗(在前一个异步任务完成后开始一个)

java - 在 AsyncTask 的 doInBackground() 方法中使用这些变量是否安全?

Android:将字符串传递给 asyncTask