1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
package com.test.downloadjpgtest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadTask extends AsyncTask<String, Void, String> {
private Activity activity;
public DownloadTask(Activity activity){
this.activity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
int idx = 0;
for (String urlString : args) {
String name = Integer.toString(++idx)+".jpg";
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException ex) {
Log.e("DownloadTask","MalformedURLException",ex);
}
saveFileOnDisk(url, name);
}
return "ok"; // just to return a string
}
protected String saveFileOnDisk(URL url, String outputName){
InputStream input = null;
try {
// in
input = url.openConnection().getInputStream();
// out
File directory = DownloadTask.getImageDirectory(this.activity);
File newFile = new File(directory, outputName);
Boolean result = newFile.createNewFile();
Log.d("DownloadTask", "newFile.createNewFile() " + result);
FileOutputStream fos = this.activity.getApplicationContext().openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = input.read(data)) != -1)
fos.write(data, 0, read);
fos.close();
return newFile.getAbsolutePath();
} catch (Exception ex) {
Log.e("TASK","Failed to download image file",ex);
} finally {
if (input != null)
try {
input.close();
}
catch (Exception ex) {
Log.e("TASK","Failed to gracefully close input stream",ex);
}
}
return "ko";
}
protected void onProgressUpdate(String... progress) {
Log.i("progress", progress[0]);
}
public static File[] getImages(Context ctxt)
{
return getImageDirectory(ctxt).listFiles();
}
public static File getImageDirectory(Context ctxt)
{
return ctxt.getDir("jpgfolder", Context.MODE_PRIVATE);
}
@Override
protected void onPostExecute(String result) {
try {
Log.d("DownloadTask", "All downloads finished");
// check downloaded files
File[] filesInDirectory = DownloadTask.getImages(this.activity);
for(int i=0, max = filesInDirectory.length; i < max; i++){
Log.i("DownloadTask", "file " + i + " > " + filesInDirectory[i] + " exist?" + filesInDirectory[i].exists());
}
// set grid adapter ... cf Main.java
((Main) this.activity).setGridAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
Partager