Wednesday, April 15, 2015

Android : Run several AsyncTask in Adroid but only when bofore task has been terminated



I need to run several times the same AsyncTask in Android (passing a different file parameter to download from FTP server), but I need one after other, not in parallel, just do this one when the other one has been terminated/finished.


So far I have this code, but it's no working properly, last task never ends:



private class FtpTask extends AsyncTask<String, Void, Integer> {
private String msg = "";
private String bean = "";

public FtpTask(String msg, String bean) {
this.msg = msg;
this.bean = bean;
}

protected void onPreExecute() {
showProgress(true, "Syncronizing", "Processing " + msg + ", wait...");
}

@Override
protected Integer doInBackground(String... params) {
if (bean.trim().equals("")) {
bean = params[0];
}
String file = Util.getMapFiles().get(bean);
int total = 0;
try {
FtpServerUtil ftp = new FtpServerUtil();
ArrayList<String> fileRows = ftp.lerArquivo(file);
total = insertRecords(bean, fileRows);
} catch (IOException e) {
Log.e(Const.TAG, "Lendo arquivo no FTP", e);
}
if (total > 0) {
Util.setSharedPrefValue("data_sinc_" + bean.toLowerCase(), Util.dateTimeToStringBR(null), context);
}
return total;
}

protected void onPostExecute(Integer total) {
showProgress(false, null, null);
String msg = "";
if (total > 0) {
msg = total + " records [" + bean + "] sincronized";
} else {
msg = "No records...";
}
Util.showToast(msg, activity);
}
}
...
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void StartAsyncTaskInParallel(FtpTask task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}
}

..
FtpTask ftpTask1 = new FtpTask("Clientes","Cliente");
FtpTask ftpTask2 = new FtpTask("Médicos","Medico");
StartAsyncTaskInParallel(ftpTask1);
StartAsyncTaskInParallel(ftpTask2);


How could I achieve that?


No comments:

Post a Comment