I am trying to create an application that is used to download an image from a server and display it in a listview. The problem I did was memory leak and application crash. I searched on an Android blog, for example, a link, this is a great idea, but this is not enough to do this with multiple threads. Some Android device can work with it, but some device can only process one thread, and sometimes it cannot work at all.
My application has a lot of activity, and each of them has a Listview, which should be displayed as quickly as possible. Through Google IO 2012, they use a buffer to save the original image on the SD card, and it solves the problem of memory leak, but makes the download so slow that the image to be downloaded was too large.
My question is: Is there a way to scale the image along with recording the image on an SD card? I will find out some possible solution is to use a Skip byte in the input object, and I was able to find the width and height and bit per pixel of the image I need to load.
The following code was used in Google IO 2012, and it works well with multiple threads, in my case I have 4 threads running in the background.
private void downloadAndWriteFile(final String url, final File file) throws OutOfMemoryError {
BufferedOutputStream out = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.connect();
final InputStream in = new BufferedInputStream(conn.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new BufferedOutputStream(new FileOutputStream(file), IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.close();
conn.disconnect();
}
catch (Exception e) {
Log.e(TAG, "!!downloadAndWriteFile " + e.getMessage());
file.delete();
}
}