Android文件下载进度条的实现代码

时间:2023-02-14 20:08:24 

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)
     {//定义一个Handler,用于处理下载线程与UI间通讯
       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, "文件下载完成", 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/");
     //下载文件,参数:第一个URL,第二个存放路径
    } 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{
     //下载函数    
     filename=url.substring(url.lastIndexOf("/") + 1);
     //获取文件名
     URL myURL = new URL(url);
     URLConnection conn = myURL.openConnection();
     conn.connect();
     InputStream is = conn.getInputStream();
     this.fileSize = conn.getContentLength();//根据响应获取文件大小
     if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
     if (is == null) throw new RuntimeException("stream is null");
     FileOutputStream fos = new FileOutputStream(path+filename);
     //把数据存入路径+文件名
     byte buf[] = new byte[1024];
     downLoadFileSize = 0;
     sendMsg(0);
     do
       {
      //循环读取
         int numread = is.read(buf);
         if (numread == -1)
         {
           break;
         }
         fos.write(buf, 0, numread);
         downLoadFileSize += numread;
         sendMsg(1);//更新进度条
       } while (true);
     sendMsg(2);//通知下载完成
     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);
 } 
}


大家看了以后就应该明白了,上面写的是用一个循环来完成的这些事情,byte buf[] = new byte[1024];这句话中大家一定要写1024,这个可不能改变呀。sendMsg(0);这句的括号里写的是0,这个也要记得,是0而不是1.

标签:Android,文件下载,进度条
0
投稿

猜你喜欢

  • 替换so文件来动态替换Flutter代码实现详解

    2023-06-23 16:24:06
  • Android TextView实现跑马灯效果的方法

    2023-07-30 20:44:12
  • idea打包java程序(包含依赖的所有jar包)

    2023-02-13 00:10:26
  • Android设置PreferenceCategory背景颜色的方法

    2021-09-24 10:13:29
  • Mybatis环境搭建及文件配置过程解析

    2021-07-04 22:37:03
  • Android实现一个带粘连效果的LoadingBar

    2023-04-26 11:47:41
  • Android WebP 图片压缩与传输

    2022-05-30 16:18:16
  • Spring createBeanInstance实例化Bean

    2023-06-17 17:26:27
  • Mybatis是这样防止sql注入的

    2022-05-30 02:05:16
  • 解决Android横竖屏切换数据丢失问题的方法

    2021-05-24 04:26:16
  • Android中RecyclerView点击Item设置事件

    2023-08-22 18:23:19
  • Java并发(Runnable+Thread)实现硬盘文件搜索功能

    2023-05-06 04:59:22
  • mybatis-plus配置控制台打印完整带参数SQL语句的实现

    2023-11-24 22:43:58
  • java web中图片验证码功能的简单实现方法

    2023-06-07 13:30:53
  • Java为什么占用四个字节你知道吗

    2021-06-16 18:05:22
  • Spring Security实现自动登陆功能示例

    2023-01-29 15:31:55
  • 关于Java中HashCode方法的深入理解

    2022-05-28 03:29:33
  • java8到java15的新功能简介

    2023-07-28 02:18:18
  • spring mvc中@RequestBody注解的作用说明

    2022-04-07 14:15:02
  • Android库项目中的资源ID冲突的解决方法

    2023-11-04 05:32:53
  • asp之家 软件编程 m.aspxhome.com