Android file download progress bar implementation code

  • 2020-05-09 19:15:24
  • OfStack

main. xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  android:id="@+id/tv"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
<ProgressBar android:id="@+id/down_pb"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:max="100"
    style="?android:attr/progressBarStyleHorizontal" mce_style="?android:attr/progressBarStyleHorizontal"
/>
</LinearLayout>

main.java:

package com.pocketdigi.download;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class main extends Activity {
    /** Called when the activity is first created. */
 ProgressBar pb;
 TextView tv;
 int   fileSize;
 int   downLoadFileSize;
 String fileEx,fileNa,filename;
 private Handler handler = new Handler()
   {
     @Override
     public void handleMessage(Message msg)
     {// define 1 a Handler , for handling the download thread and UI Communication between 
       if (!Thread.currentThread().isInterrupted())
       {
         switch (msg.what)
         {
           case 0:
             pb.setMax(fileSize);
           case 1:
             pb.setProgress(downLoadFileSize);
             int result = downLoadFileSize * 100 / fileSize;
             tv.setText(result + "%");
             break;
           case 2:
             Toast.makeText(main.this, " File download completed ", 1).show();
             break;
           case -1:
             String error = msg.getData().getString("error");
             Toast.makeText(main.this, error, 1).show();
             break;
         }
       }
       super.handleMessage(msg);
     }
   };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pb=(ProgressBar)findViewById(R.id.down_pb);
        tv=(TextView)findViewById(R.id.tv);
        new Thread(){
         public void run(){
          try {
     down_file("http://wallpaper.pocketdigi.com/upload/1/bigImage/1284565196.jpg","/sdcard/");
     // Download file, parameters: first 1 a URL In the first 2 Individual storage path 
    } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
         }
        }.start();
    }
    public void down_file(String url,String path) throws IOException{
     // Download function     
     filename=url.substring(url.lastIndexOf("/") + 1);
     // Get file name 
     URL myURL = new URL(url);
     URLConnection conn = myURL.openConnection();
     conn.connect();
     InputStream is = conn.getInputStream();
     this.fileSize = conn.getContentLength();// Gets the file size based on the response 
     if (this.fileSize <= 0) throw new RuntimeException(" Cannot know file size  ");
     if (is == null) throw new RuntimeException("stream is null");
     FileOutputStream fos = new FileOutputStream(path+filename);
     // Put the data into the path + The file name 
     byte buf[] = new byte[1024];
     downLoadFileSize = 0;
     sendMsg(0);
     do
       {
      // Loop reads 
         int numread = is.read(buf);
         if (numread == -1)
         {
           break;
         }
         fos.write(buf, 0, numread);
         downLoadFileSize += numread;
         sendMsg(1);// Update progress bar 
       } while (true);
     sendMsg(2);// Notification download completed 
     try
       {
         is.close();
       } catch (Exception ex)
       {
         Log.e("tag", "error: " + ex.getMessage(), ex);
       }
    }
 private void sendMsg(int flag)
 {
     Message msg = new Message();
     msg.what = flag;
     handler.sendMessage(msg);
 }  
}

And you'll see that when you look at it, it says this is done in a loop, byte buf[] = new byte[1024]; You must write 1024 in this sentence. You can't change that. sendMsg (0); This is a 0 in parentheses, and remember this is a 0 instead of a 1.

Related articles: