Android文件下载进度条的实现

来源:互联网 发布:js获取当前触发事件 编辑:程序博客网 时间:2024/05/17 03:18
[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical"    
  4.     android:layout_width="fill_parent"    
  5.     android:layout_height="fill_parent"    
  6.     >    
  7. <TextView  android:id="@+id/tv"    
  8.     android:layout_width="fill_parent"     
  9.     android:layout_height="wrap_content"     
  10.     android:text=""    
  11.     />    
  12. <ProgressBar android:id="@+id/down_pb"    
  13.     android:layout_width="fill_parent"     
  14.     android:layout_height="wrap_content"    
  15.     android:max="100"    
  16.     style="?android:attr/progressBarStyleHorizontal" mce_style="?android:attr/progressBarStyleHorizontal"    
  17. />    
  18. </LinearLayout>   

main.java:

[html] view plaincopy
  1. package com.pocketdigi.download;    
  2.      
  3. import java.io.FileOutputStream;    
  4. import java.io.IOException;    
  5. import java.io.InputStream;    
  6. import java.net.URL;    
  7. import java.net.URLConnection;    
  8.      
  9. import org.apache.http.client.ClientProtocolException;    
  10. import android.app.Activity;    
  11. import android.os.Bundle;    
  12. import android.os.Handler;    
  13. import android.os.Message;    
  14. import android.util.Log;    
  15. import android.widget.ProgressBar;    
  16. import android.widget.TextView;    
  17. import android.widget.Toast;    
  18.      
  19. public class main extends Activity {    
  20.     /** Called when the activity is first created. */    
  21.     ProgressBar pb;    
  22.     TextView tv;    
  23.     int   fileSize;    
  24.     int   downLoadFileSize;    
  25.     String fileEx,fileNa,filename;    
  26.     private Handler handler = new Handler()    
  27.       {    
  28.         @Override    
  29.         public void handleMessage(Message msg)    
  30.         {//定义一个Handler,用于处理下载线程与UI间通讯    
  31.           if (!Thread.currentThread().isInterrupted())    
  32.           {    
  33.             switch (msg.what)    
  34.             {    
  35.               case 0:    
  36.                 pb.setMax(fileSize);    
  37.               case 1:    
  38.                 pb.setProgress(downLoadFileSize);    
  39.                 int result = downLoadFileSize * 100 / fileSize;    
  40.                 tv.setText(result + "%");    
  41.                 break;    
  42.               case 2:    
  43.                 Toast.makeText(main.this, "文件下载完成", 1).show();    
  44.                 break;    
  45.      
  46.               case -1:    
  47.                 String error = msg.getData().getString("error");    
  48.                 Toast.makeText(main.this, error, 1).show();    
  49.                 break;    
  50.             }    
  51.           }    
  52.           super.handleMessage(msg);    
  53.         }    
  54.       };    
  55.     @Override    
  56.     public void onCreate(Bundle savedInstanceState) {    
  57.         super.onCreate(savedInstanceState);    
  58.         setContentView(R.layout.main);    
  59.         pb=(ProgressBar)findViewById(R.id.down_pb);    
  60.         tv=(TextView)findViewById(R.id.tv);    
  61.         new Thread(){    
  62.             public void run(){    
  63.                 try {    
  64.        down_file("http://wallpaper.pocketdigi.com/upload/1/bigImage/1284565196.jpg",  
  65. "/sdcard/");    
  66.                     //下载文件,参数:第一个URL,第二个存放路径    
  67.                 } catch (ClientProtocolException e) {    
  68.                     // TODO Auto-generated catch block    
  69.                     e.printStackTrace();    
  70.                 } catch (IOException e) {    
  71.                     // TODO Auto-generated catch block    
  72.                     e.printStackTrace();    
  73.                 }    
  74.             }    
  75.         }.start();    
  76.      
  77.      
  78.     }    
  79.     public void down_file(String url,String path) throws IOException{    
  80.         //下载函数          
  81.         filename=url.substring(url.lastIndexOf("/") + 1);    
  82.         //获取文件名    
  83.         URL myURL = new URL(url);    
  84.         URLConnection conn = myURL.openConnection();    
  85.         conn.connect();    
  86.         InputStream is = conn.getInputStream();    
  87.         this.fileSize = conn.getContentLength();//根据响应获取文件大小    
  88.         if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");    
  89.         if (is == null) throw new RuntimeException("stream is null");    
  90.         FileOutputStream fos = new FileOutputStream(path+filename);    
  91.         //把数据存入路径+文件名    
  92.         byte buf[] = new byte[1024];    
  93.         downLoadFileSize = 0;    
  94.         sendMsg(0);    
  95.         do    
  96.           {    
  97.             //循环读取    
  98.             int numread = is.read(buf);    
  99.             if (numread == -1)    
  100.             {    
  101.               break;    
  102.             }    
  103.             fos.write(buf, 0, numread);    
  104.             downLoadFileSize += numread;    
  105.      
  106.             sendMsg(1);//更新进度条    
  107.           } while (true);    
  108.         sendMsg(2);//通知下载完成    
  109.         try    
  110.           {    
  111.             is.close();    
  112.           } catch (Exception ex)    
  113.           {    
  114.             Log.e("tag", "error: " + ex.getMessage(), ex);    
  115.           }    
  116.      
  117.     }    
  118.     private void sendMsg(int flag)    
  119.     {    
  120.         Message msg = new Message();    
  121.         msg.what = flag;    
  122.         handler.sendMessage(msg);    
  123.     }        
  124.      
  125.      
  126. }    
0 0