Created
March 28, 2016 13:25
-
-
Save laszlo-galosi/ce9604bc5648ee38acf4 to your computer and use it in GitHub Desktop.
Bitmap downloader AsyncTask with determinate progress and counter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected Bitmap doInBackground(String... urls) { | |
Bitmap bitmap = null; | |
try { | |
HttpURLConnection connection = (HttpURLConnection) new URL(urls[0]).openConnection(); | |
connection.setRequestProperty("User-agent", "Mozilla/4.0"); | |
connection.setRequestMethod("GET"); | |
connection.connect(); | |
InputStream in = null; | |
int responseCode = connection.getResponseCode(); | |
if (responseCode == HttpURLConnection.HTTP_OK) { | |
in = connection.getInputStream(); | |
} | |
int length = connection.getContentLength(); | |
byte[] data = new byte[length]; | |
int increment = length / 10; | |
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); | |
int count = -1; | |
int progress = 0; | |
while ((count = in.read(data, 0, increment)) != -1) { | |
progress += count; | |
mCounter = (progress * 10) / length; | |
publishProgress(mCounter); | |
outStream.write(data, 0, count); | |
} | |
bitmap = BitmapFactory.decodeByteArray(outStream.toByteArray(), 0, data.length); | |
in.close(); | |
outStream.close(); | |
} catch (Throwable throwable) { | |
Log.e("Error", throwable.getMessage()); | |
} | |
return bitmap; | |
} | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
mCounter = 0; | |
textView.setText(String.format("%d", mCounter)); | |
} | |
@Override | |
protected void onProgressUpdate(Integer... values) { | |
super.onProgressUpdate(values); | |
textView.setText(String.format("%d", values[0])); | |
} | |
@Override | |
protected void onPostExecute(Bitmap bitmap) { | |
imageView.setImageBitmap(bitmap); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment