我的启动画面中有多个asynctask在for循环中运行。我希望应用程序在所有异步任务完成之前停止执行。我想用异步任务的总数和任务的完成来更新UI线程,例如如果有3个任务和1个完成,我想显示1 / 3完成。这是循环的代码:-
String[] images = Parse_imgJSON.image;
for (int i = 0; i < images.length; i++) {
Log.d("Image ", images[i]);
download_img(images[i]);
}
download_img()的代码:-
public void download_img(String img_url) {
String fileName = img_url.substring(img_url.lastIndexOf('/') + 1, img_url.length());
File file = new File("/storage/emulated/0/rready_images/" + fileName);
if (file.exists() && !file.isDirectory()) {
Log.d("Image exists", fileName);
} else {
if (fileName.contains(".jpg") || fileName.contains(".gif") || fileName.contains(".png")) {
new DownloadImagesAsync().execute(img_url);
} else {
Log.d("IMAGE DOWNLOAD ", "FAILED FOR " + fileName);
}
}
}
用于下载文件的实际异步任务代码:-
class DownloadImagesAsync extends AsyncTask<String, String, String> {
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
int lengthOfFile;
@Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/rreadyreckoner_images/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/rreadyreckoner_images/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
@Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename + " Downloaded ");
String fname = filename.substring(filename.lastIndexOf('/') + 1, filename.length());
Log.d("LENGTH OF FILE : ", String.valueOf(lengthOfFile));
if (isSDPresent) {
File f = new File("/storage/emulated/0/rreadyreckoner_images/" + fname);
if (f.length() < lengthOfFile) {
if (f.delete()) {
// Toast.makeText(RReadySplash.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del", "File deleted");
} else {
Log.d("NOTDel", "File not deleted");
}
} else {
// dbHandler.updateDownloadStatus(image_id, "YES");
}
} else {
File f = new File("/storage/emulated/0/rreadyreckoner_images/" + fname);
if (f.length() < lengthOfFile) {
if (f.delete()) {
Log.d("Del", "File deleted");
} else {
Log.d("NOTDel", "File not deleted");
}
} else {
// dbHandler.updateDownloadStatus(image_id, "YES");
}
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
}
}
任何帮助或建议,表示赞赏。谢谢你。
有很多方法。
例如,您可以使用接口回调。
创建一个接口:
public interface MyCallback {
public void readycallback(int index_thread);
}
改变类:
class DownloadImagesAsync extends AsyncTask<String, String, String> {
private int id = 0;
private MyCallback callback;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
int lengthOfFile;
public DownloadImagesAsync(int id, MyCallback callback) {
this.id = id;
this.callback = callback;
}
@Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/rreadyreckoner_images/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/rreadyreckoner_images/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
@Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename + " Downloaded ");
if (callback != null) {
callback.readycallback(myid);
}
String fname = filename.substring(filename.lastIndexOf('/') + 1, filename.length());
Log.d("LENGTH OF FILE : ", String.valueOf(lengthOfFile));
if (isSDPresent) {
File f = new File("/storage/emulated/0/rreadyreckoner_images/" + fname);
if (f.length() < lengthOfFile) {
if (f.delete()) {
// Toast.makeText(RReadySplash.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del", "File deleted");
} else {
Log.d("NOTDel", "File not deleted");
}
} else {
// dbHandler.updateDownloadStatus(image_id, "YES");
}
} else {
File f = new File("/storage/emulated/0/rreadyreckoner_images/" + fname);
if (f.length() < lengthOfFile) {
if (f.delete()) {
Log.d("Del", "File deleted");
} else {
Log.d("NOTDel", "File not deleted");
}
} else {
// dbHandler.updateDownloadStatus(image_id, "YES");
}
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
}
}
使用此类更改主函数
String[] images = Parse_imgJSON.image;
for (int i = 0; i < images.length; i++) {
Log.d("Image ", images[i]);
download_img(images[i], i);
}
public void download_img(String img_url, int i) {
String fileName = img_url.substring(img_url.lastIndexOf('/') + 1, img_url.length());
File file = new File("/storage/emulated/0/rready_images/" + fileName);
if (file.exists() && !file.isDirectory()) {
Log.d("Image exists", fileName);
} else {
if (fileName.contains(".jpg") || fileName.contains(".gif") || fileName.contains(".png")) {
new DownloadImagesAsync(i, new MyCallback() {
@Override
public void readycallback(int index_thread) {
//this is your ready callback
}
}).execute(img_url);
} else {
Log.d("IMAGE DOWNLOAD ", "FAILED FOR " + fileName);
}
}
}
不要忘记检查您是否使用主UI线程:
如果需要,可以通过以下功能包装更新:
@Override
public void readycallback(int index_thread) {
//this is your ready callback
runOnUiThread(new Runnable() {
@Override
public void run() {
//this is your ready callback in main UI
//I do not remember if onPostExecute is in main UI thread
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句