安卓:异步任务并行执行问题



有一个异步任务,它针对函数中的不同情况模拟调用  当前正在发生的事情:在执行任务 2 的 doinBackground 后,当调用任务 2 的 onPostExecute 时,它返回包含与任务 1 和任务 2 对应的输出的列表,如下所述  实际O/P onPostExecute:/path/Test1.txt onPostExecute:/path/Test2.txt

预期盈利 onPostExecute:/path/Test2.txt

我们如何在 Post 执行中独立维护对应于每个案例的列表(目前这是静态列表(


异步任务类 -->

static ArrayList<String> listOfCopiedFiles = new ArrayList<>();
protected Boolean doInBackground(String... params) {
boolean sucssees_fail = true;
listOfCopiedFiles.clear();
sucssees_fail = copyDirectoryOneLocationToAnotherLocation(srccopy, dst);
//copyDirectoryOneLocationToAnotherLocation(srccopy, dst) : Returns Boolean and add the file in    "listOfCopiedFiles" which is static array list
}

protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result)
{   Log.d(TAG,"delegate.onSuccess");
delegate.onSuccess(ServiceIntent, listOfCopiedFiles);
// on success passes the list of files 
}
}

调用类 -->

case Type1:
srcCopydir = Dir1
copyfilename = file1;               
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;  
case Type2:              
srcCopydir = Dir2
copyfilename = file2;
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
case Type3:
srcCopydir = Dir3;
copyfilename = file3
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
case Type4:
srcCopydir = Dir3;
copyfilename = file3
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;

这个 calss 通过读取解析的 xml 来接收意图,其中包含上述所有类型

每次收到意向时,都会为异步任务创建新对象。

问题: 当问题类型1的任务正在进行(doInBackground(时,收到其他"案例"的意图,因此也开始执行其他案例

在案例 1 的"onPostExecute"称为案例 2 完成之前有时会发生的事情,在案例 1 中,它给出 o/p,即"列表复制文件",这是案例 2 的预期

我尝试在调用delegate.onSuccess(ServiceIntent,listOfCopiedFiles(后立即清除"onPostExecute"中的"listOfCopiedFiles",但它似乎不起作用

Boolean chk;
delegate.onSuccess(ServiceIntent, listOfCopiedFiles);
for(String list :listOfCopiedFiles){             
chk = listOfCopiedFiles.remove(list);
}

还尝试在"onPostExecute"的临时数组列表中复制 listOfCopiedFiles 并在"onPostExecute"中出现控件后立即清除它,但它也不起作用

Boolean chk;
chk= copyPathTempList.addAll(listOfCopiedFiles);
listOfCopiedFiles.clear();
delegate.onSuccess(ServiceIntent, copyPathTempList);
copyPathTempList.clear();

 

我想你的问题是不恰当的,因为从 AsyncTask API 文档:

线程规则说,

该任务只能执行一次(如果尝试第二次执行,将引发异常。

最新更新