我有以下AsyncTask
public class LoadFromCloudTask extends AsyncTask<Void, String, Boolean> {
public LoadFromCloudTask(LoadFromCloudTaskFragment loadFromCloudTaskFragment) {
this.loadFromCloudTaskFragment = loadFromCloudTaskFragment;
}
@Override
protected Boolean doInBackground(Void... params) {
...
...
...
// How possible I can halt my execution, prompt for user input, and continue execution based on user input.
// In Swing, I can ...
//
/*
// Hold the execution, and prompt for user input
final int result = JOptionPane.showConfirmDialog(LoadFromCloudJDialog.this, message, MessagesBundle.getString("question_title_overwrite_your_data_by_cloud_data_at"), JOptionPane.YES_NO_OPTION);
// Continue execution based on user input.
*/
}
}
我想知道,是否可以暂停AsyncTask执行,提示用户输入并根据用户输入继续执行?
在Swing中,我可以通过简单地使用JOptionPane.showConfirmDialog
来实现这一点。 Android怎么样?
答案 0 :(得分:1)
由于doInBackground
在不同的线程中执行,您必须在UI线程中显示一些dialog时暂停此线程,一旦对话框解除,您可以恢复AsyncTask
并阅读结果。
答案 1 :(得分:1)
检查Asynctask 的文档,您可以取消并重新启动异步任务,因为The task can be executed only once
你想要这样的东西ideal-way-to-cancel-an-executing-asynctask
doInBackground不在UI线程中执行,因此您可以执行显示对话框的UI操作
答案 2 :(得分:1)
您可以通过publishProgress
内部使用doInBackground(Params...)
向 UIThread 发送消息来实现此目的,并使用java的 wait / notify 机制来等待untel用户输入他的输入。
psudo代码看起来像这样:
public Object mLock = new Object();
protected void doInBackground(Params... params){
/// do your requests.
publishProgress(Progress ...progress);
mLock.wait();
}
protected void onProgressUpdate(Progress ....progress) {
// request user input here
}
并从您的UIThread中调用mLock.notify()
,让代码继续。
此外,您可以通过在多个AsynchTasks之间拆分逻辑来执行更加简洁的行为,因为AsynchTasks由共享(静态)ThreadPoolExecutor和
管理,因此不会非常昂贵答案 3 :(得分:1)
You can create pause and resume method inside asyntask as below, and call it according to your convenience.
public class LoadFromCloudTask extends AsyncTask<Void, String, Boolean> {
public LoadFromCloudTask(LoadFromCloudTaskFragment loadFromCloudTaskFragment) {
this.loadFromCloudTaskFragment = loadFromCloudTaskFragment;
}
//call this when you want to halt the task
public void pause() {
if (this.getStatus().equals(Status.RUNNING)) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// call this when you need to resume the task
public void resume() {
if (this.getStatus().equals(Status.PENDING)) {
this.notify();
}
}
@Override
protected Boolean doInBackground(Void... params) {
...
...
...
// How possible I can halt my execution, prompt for user input, and continue execution based on user input.
// In Swing, I can ...
//
/*
// Hold the execution, and prompt for user input
final int result = JOptionPane.showConfirmDialog(LoadFromCloudJDialog.this, message, MessagesBundle.getString("question_title_overwrite_your_data_by_cloud_data_at"), JOptionPane.YES_NO_OPTION);
// Continue execution based on user input.
*/
}
}