Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyAsync extends AsyncTask<String, Integer, Bitmap> {
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- dialog = new ProgressDialog(MainActivity.this);
- dialog.setTitle("Downloading...");
- dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- dialog.show();
- dialog.setMax(100);
- }
- @Override
- protected void onPostExecute(Bitmap bitmap) {
- imageView.setImageBitmap(bitmap);
- dialog.dismiss();
- super.onPostExecute(bitmap);
- }
- @Override
- protected void onProgressUpdate(Integer... values) {
- super.onProgressUpdate(values);
- dialog.setProgress(values[0]);
- }
- @Override
- protected Bitmap doInBackground(String... params) {
- try {
- URL url = new URL(params[0]);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.connect();
- InputStream input = connection.getInputStream();
- int total = connection.getContentLength();
- int downloaded = 0;
- int bytesCount;
- byte[] imageData = new byte[10000];
- File file = new File(getFilesDir().getPath() + "tempFile");
- if (!file.exists()) {
- file.createNewFile();
- }
- FileOutputStream cacheFile = new FileOutputStream(file);
- while ((bytesCount = input.read(imageData)) > 0) {
- downloaded += bytesCount;
- publishProgress((downloaded * 100) / total);
- cacheFile.write(imageData, 0, bytesCount);
- }
- cacheFile.close();
- Bitmap myBitmap = BitmapFactory.decodeFile(getFilesDir().getPath() + "tempFile");
- file.delete();
- return myBitmap;
- } catch (IOException e) {
- return null;
- }
- }
- }
Add Comment
Please, Sign In to add comment