我有多个asynctask在我的启动画面中的for循环中运行。 我希望应用程序停止执行,直到所有的asynctasks完成。并且我想用异步任务总数和任务完成来更新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]); } }任何帮助或建议表示赞赏。 谢谢。
I have multiple asynctask's running in a for loop inside my splash screen. I want the app to stop execution until all the asynctasks are complete.And I would like to update the UI thread with the total number of async task and task's completed.Like if there are 3 tasks and 1 is complete I would like to display 1/3 complete. This is code for the loop:-
String[] images = Parse_imgJSON.image; for (int i = 0; i < images.length; i++) { Log.d("Image ", images[i]); download_img(images[i]); }Code for 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); } } }The actual Async Task code for downloading file:-
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]); } }Any help or suggestion is appreciated. Thank you.
最满意答案
有很多方法。
例如,你可以使用接口回调。
创建一个界面:
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 } }); }There are a lot of methods.
For example, you can use interface callbacks.
Create an interface:
public interface MyCallback { public void readycallback(int index_thread); }change the class:
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]); } }to use this class change main function
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); } } }Do not forget to check whether you using main UI thread:
if you need you may wrap updates by this function:
@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 } }); }更多推荐
发布评论