package net.atoom.android.dbt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import net.atoom.android.dbt.util.LogBridge;
import android.os.AsyncTask;
import android.os.Environment;
public class LoadTestImages extends
AsyncTask<List<BabeTestQuestion>, Void, Void> {
private static final int IO_BUFFER_SIZE = 4 * 1024;
private BabeTest m_test;
public LoadTestImages(BabeTest test) {
m_test = test;
}
@Override
protected Void doInBackground(List<BabeTestQuestion>... params) {
for (BabeTestQuestion question : params[0]) {
String imagePath = question.getFileName();
String[] pathParts = imagePath.split("/");
String imageName = pathParts[pathParts.length - 1];
try {
loadImage(imageName, BabeTest.BASE_URL + imagePath);
m_test.imageLoaded(question);
} catch (IOException e) {
LogBridge.w(e.getMessage());
}
}
return null;
}
private void loadImage(String fileName, String fileUrl) throws IOException {
boolean storageAvailable = false;
boolean storageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
storageAvailable = storageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
storageAvailable = true;
storageWriteable = false;
} else {
storageAvailable = storageWriteable = false;
}
if (!storageWriteable) {
return;
}
File root = Environment.getExternalStorageDirectory();
File cache = new File(root, BabeTest.STORE_DIR);
cache.mkdir();
File imageFile = new File(cache, fileName);
if (imageFile.exists()) {
return;
}
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream(),
IO_BUFFER_SIZE);
final FileOutputStream outStream = new FileOutputStream(imageFile);
out = new BufferedOutputStream(outStream, IO_BUFFER_SIZE);
byte[] bytes = new byte[IO_BUFFER_SIZE];
while (in.read(bytes) > 0) {
out.write(bytes);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LogBridge.w(e.getMessage());
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
LogBridge.w(e.getMessage());
}
}
}
}
}
|