在循环中多次执行asynctask或并行执行asynctask

时间:2017-11-09 16:57:41

标签: android android-studio exception android-asynctask

代码

  for (int i=0;i<imagesURL.length();i++)
    {
        final JSONObject obj = imagesURL.getJSONObject(i);
       // obj1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,obj.getString("source"));
        obj1.execute(obj.getString("source")).get();

    }

我试过了

  

AsyncTask.THREAD_POOL_EXECUTOR

  

.execute.get();

但是asynctask导致execption。我只想完全执行这个循环,当第一个任务完全执行然后再执行。

错误

Process: com.dexquad.posttracker, PID: 11481
                                                                     java.lang.IllegalStateException: Cannot execute task: the task is already running.
                                                                         at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:593)
                                                                         at android.os.AsyncTask.execute(AsyncTask.java:551)
                                                                         at com.dexquad.posttracker.TimelineActivity.processUserPhotosResult(TimelineActivity.java:224)
                                                                         at com.dexquad.posttracker.TimelineActivity$4.onCompleted(TimelineActivity.java:181)
                                                                         at com.facebook.GraphRequest$5.run(GraphRequest.java:1380)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                         at android.app.ActivityThreadHook.handleMain(ActivityThreadHook.java:27)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

在for循环中创建AsyncTask的单个实例。

for(..){
    //
    new MyAsyncTask().execute(obj.getString("source"));
}