我的Fragment中有4个AsyncTask类。我想执行所有这四个,但一次一个。我尝试过task.execute()。get()和task.execute()。getStatus()。这些似乎不能正常工作 - 我得到一个错误,我无法在任务运行时执行另一项任务。这些是我试图运行的4个AsyncTasks:
ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setTitle("Finalizing Your Run");
dialog.setMessage("We hope you had fun running! Please wait while we send your running data to our system. This may take a few seconds depending on your internet connection");
dialog.setCancelable(false);
dialog.show();
//All the async tasks to be executed
AddRouteCheckpoints checkpointTask = new AddRouteCheckpoints(getActivity(), dialog);
GetRouteIdTask routeIdTask = new GetRouteIdTask(getActivity(), dialog);
AddRouteTask addRouteTask = new AddRouteTask(getActivity(), dialog);
AddRunTask personalRunTask = new AddRunTask(getActivity(), dialog);
在继续下一个AsyncTask之前,有没有办法确保每个AsyncTask完成其任务?
答案 0 :(得分:2)
为什么不在SingleThreadExecutor中执行那些AsyncTasks?
Executor executor = Executors.newSingleThreadExecutor();
然后在执行者身上执行任务:
task.executeOnExecutor(executor);
这样只会使用一个线程来运行AsyncTasks,其他线程将排队。
答案 1 :(得分:0)
答案 2 :(得分:0)
前几天我也有同样的情况。我以这种方式解决了它:将您的活动的引用传递给异步类的构造函数并执行do in background函数。现在在post执行函数中,从异步类调用ur活动的公共方法再次执行任务...或者试试这个:
if (asynclass.getStatus() == android.os.AsyncTask.Status.PENDING) {
asynclass.execute();
} else if (RF.getStatus() == android.os.AsyncTask.Status.FINISHED) {
asynclass = new asyncclass();
asynclass.execute();
} else {
Toast.maketoast(this, "Plz wait", 1).show();
}
或者您可以按照以下方式进行操作
您可以使用myAsyncTask.executeOnExecutor(SERIAL_EXECUTOR)
进行此操作AsyncTask a = new AsyncTask();
AsyncTask b = new AsyncTask();
AsyncTask c = new AsyncTask();
a.executeOnExecutor (SERIAL_EXECUTOR);
b.executeOnExecutor (SERIAL_EXECUTOR);
c.executeOnExecutor (SERIAL_EXECUTOR);
干杯