I am using AsyncTask to start a background operation. Of course, switching to another thread, although it is already running in the background thread, does not make much sense at all, except that the other thread is a user interface thread. This is what I would like: during the execution of the task, I need to “access” the user interface, for example. to show a dialog box to ask the user how to proceed.
- complete background task
- stop the task at some point to get user feedback.
- switch to UI thread to display a dialog box and request input
- Go back to the background task and continue.
How can I do that? I thought I could use Runnablewith myActivity.runOnUiThread(runnable), but this does not work:
private void copyFiles() {
CopyTask copyTask = new CopyTask(this);
copyTask.execute();
}
private class CopyTask extends CustomAsyncTask<Void, Void, Void> {
private doCopy;
@Override
protected Boolean doInBackground(Void... params) {
for (File file : allFiles) {
doCopy = true;
if (isConflict(file)) {
Runnable uiRunnable = new Runnable() {
public void run() {
doCopy = false;
synchronized (this) {
this.notify();
}
}
});
synchronized(uiRunnable) {
activity.runOnUiThread(uiRunnable);
try {
uiRunnable.wait();
}
catch (InterruptedException e ) {
e.printStackTrace();
}
}
}
if (doCopy)
copyFromAToB(File);
}
return null;
}
}
Inside doInBackground()(-> in the background thread) AsyncTaskcalls activity.runOnUiThread(uiRunnable). The following is called uiRunnable.wait(). Regarding document wait() , you need to do the following:
Causes the calling thread to wait until another thread calls notify () or notifyAll () of this object.
Thus, the background thread must wait for its work to continue until this.notify()(== uiRunnable.notifiy()) is called into another thread (= UI thread), right?
, id ! uiRunnable.wait() , if (doCopy).... , (, , ...) , , , doCopy = false if (doCopy) .
? wait() , ? - ?
!
EDIT:
: , AsyncTask, , , , (. ).
AsyncTask, , AsyncTask , . , //.
wait(), . , AsyncTask, wait() , .