2

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.

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?

4

3 回答 3

4

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

  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
于 2012-07-24T18:56:49.280 回答
1

您可以使用 a Callable,将其提交给 an Executor,然后Executor将返回FutureTask然后您将while循环等待,直到FutureTask.isDone == true

这是一个示例http://programmingexamples.wikidot.com/futuretask

于 2012-07-24T18:46:22.187 回答
1

我希望我的回答一定能解决你的问题。

//在 AsyncTask 的 doInBackground() 方法中执行以下所有代码

String userInput="";

        YouActivity.this.runOnUiThread(new Runnable() {

            public void run() {


            //SHOW YOUR DIALOG HERE

            }
        });


        while("".equals(userInput))
        {
            YouActivity.this.runOnUiThread(new Runnable() {

                public void run() {

                userInput=editText.getText().toString();//fetching user input from edit Text    
                }
            });

        }

谢谢 :)

于 2012-07-24T18:27:26.597 回答