AsyncTask download picture with progress bar

main_activity.xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.mrzhao.imagedemo.MainActivity">
    <Button
android:layout_width=                        
        "match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="点击下载图片"
tools:ignore="OnClick" />
    <ImageView
android:id="@+id/show_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>                                
                        

MainActivity file:

public class MainActivity extends AppCompatActivity {

    private String path = "http://f2.dn.anqu.com/down/ZmQ1MA==/allimg/1208/48-120PQ61324.jpg" ;
     private ImageView showIv ;
 //Progress pop-up box
 private ProgressDialog dialog ;
 @Override
 protected void onCreate (Bundle savedInstanceState) {
         super .onCreate(savedInstanceState) ;
 setContentView(R.layout.activity_main ) ;
 showIv = (ImageView) findViewById( R.id.show_iv ) ;
 //The parameter of the instantiation progress popup box is a context object
 dialog = new        
                        
                ProgressDialog( this ) ;
 //Set the maximum progress
 dialog .setMax( 100 ) ;
 //Set the title
 dialog .setTitle( "Prompt" ) ;
 //Set the display information
 dialog .setMessage( "Loading, please wait ..." ) ;
 //Set the horizontal progress bar
 dialog .setProgressStyle(ProgressDialog. STYLE_HORIZONTAL ) ;
 }                                                                    

    public void onClick (View view) {
         //Click to download the picture
 new MyTask().execute() ;
 }
        
    

    /**
      * Asynchronous task for downloading images
      */
 class MyTask extends AsyncTask<String , Integer , Bitmap> {    

        @Override
 protected void onPreExecute () {
             super .onPreExecute() ;
 //Prepare to show the pop-up box!
dialog.show () ;
 }                                
        

        @Override
protected Bitmap doInBackground(String... strings) {        

            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(30 * 1000);
                conn.setReadTimeout(30 * 1000);
// 获取文件总大小
int total = conn.getContentLength();
conn.connect();
                if (conn.getResponseCode() == 200) {                                
                
                    inputStream = conn.getInputStream() ;
                     outputStream = new ByteArrayOutputStream() ;
                     int len ​​= 0 ;
                     int   current= 0 ;
                     byte [] bytes = new byte [ 1024 ] ;
                     while ((len = inputStream.read(bytes)) != - 1 ) {
                         //Simulate delayed download progress
                         Thread.sleep ( 100 ) ;
 //Overlay calculate the size of downloaded files
 current +=len ;
                                                                        outputStream.write(bytes , 0 , len) ;
 //The size of the downloaded file divided by the total size of the file multiplied by 100% progress!
int progress = ( int ) ((current / ( float )total) * 100 ) ;
 // update progress
 publishProgress(progress) ;
 }
                     // Convert OutputStream to array
 byte [] bitmapBytes = outputStream.toByteArray() ;
 // Will Convert the array to a picture object
 Bitmap bitmap = BitmapFactory. decodeByteArray (bitmapBytes , 0 , bitmapBytes. length ) ;
                     return
                                                                                                
                                                                                bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
 protected void onProgressUpdate (Integer... values) {
             super .onProgressUpdate(values) ;
 //Update progress setting progress
 dialog .setProgress(values[ 0 ]) ;
 }                                        

        @Override
 protected void onPostExecute (Bitmap bitmap) {
             super .onPostExecute(bitmap) ;
 //Close the dialog
 dialog .dismiss() ;
             if (bitmap != null ) {
                 //Show the picture
 showIv .setImageBitmap(bitmap) ;
 }                                                            
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324682304&siteId=291194637