因为在项目开发时。有这种简单需求,问谷歌,网络上也有好多Utils工具类,可是比較冗余。自己就简单的写了一个简单帮助类。


/**
* 下载文件,更新UI简单帮助类
*
* @author jarlen
*
*/
public class DownLoadHelper
{
private static final int DOWN_BEGIN = 0;
private static final int DOWN_UPDATA = 1;
private static final int DOWN_FINISH = 2;
private static final int DOWN_ERROR = 3; private Context mContext; private TextView mTextView; private ProgressBar mBar; private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if (!Thread.currentThread().isInterrupted())
{
switch (msg.what)
{
case DOWN_BEGIN:
if (mTextView != null)
{
mTextView.setText("開始下载");
} if(mBar != null)
{
mBar.setProgress(0);
} break;
case DOWN_UPDATA:
int factor = msg.arg1; if (mTextView != null)
{
mTextView.setText(factor + "%");
} if(mBar != null)
{
mBar.setProgress(factor);
} break; case DOWN_FINISH:
if (mTextView != null)
{
mTextView.setText("下载完毕");
} if(mBar != null)
{
mBar.setProgress(100);
} break;
case DOWN_ERROR:
if (mTextView != null)
{
mTextView.setText("下载错误");
} if(mBar != null)
{
mBar.setProgress(0);
} break; default:
break;
}
}
};
}; public DownLoadHelper(Context context)
{
this.mContext = context;
} /**
* 设置下载时,须要更新的UI TextView
* @param view
*/
public void setUpdataView(TextView view)
{
this.mTextView = view;
} /**
* 设置下载时,须要更新的UI,ProgressBar
* @param bar
*/
public void setUpdataBar(ProgressBar bar)
{
this.mBar = bar;
} /**
* 開始下载
* @param url
* 文件下载地址
* @param path
* 文件保存地址
*/
public void startDownLoad(final String url, final String path)
{ new Thread()
{
public void run()
{
sendMsg(DOWN_BEGIN, 0);
try
{
long downloadSize = downloadUpdateFile(url, path);
if (downloadSize > 0)
{
sendMsg(DOWN_FINISH, 0);
}
} catch (Exception e)
{
e.printStackTrace();
sendMsg(DOWN_ERROR, 0);
} };
}.start();
} private long downloadUpdateFile(String down_url, String path)
throws Exception
{
int down_step = 1;// 提示step
int totalSize;// 文件总大小
int downloadCount = 0;// 已经下载好的大小
int updateCount = 0;// 已经上传的文件大小
InputStream inputStream;
OutputStream outputStream;
URL url = new URL(down_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(30 * 1000);
httpURLConnection.setReadTimeout(30 * 1000);
// 获取下载文件的size
totalSize = httpURLConnection.getContentLength();
if (httpURLConnection.getResponseCode() == 404)
{
sendMsg(DOWN_ERROR, 0);
throw new Exception("fail!");
}
inputStream = httpURLConnection.getInputStream();
File dir = new File(path);
if (!dir.exists())
{
dir.mkdir();
}
String name = down_url.substring(down_url.lastIndexOf("/") + 1,
down_url.length()); File updateFile = new File(dir, name);
outputStream = new FileOutputStream(updateFile, false);// 文件存在则覆盖掉
byte buffer[] = new byte[1024];
int readsize = 0;
while ((readsize = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, readsize);
downloadCount += readsize;// 时时获取下载到的大小
// 每次增长1%
if (updateCount == 0
|| (downloadCount * 100 / totalSize - down_step) >= updateCount)
{
updateCount += down_step;
sendMsg(DOWN_UPDATA, updateCount); }
}
if (httpURLConnection != null)
{
httpURLConnection.disconnect();
}
inputStream.close();
outputStream.close();
return downloadCount;
} private void sendMsg(int flag, int factor)
{
Message msg = new Message();
switch (flag)
{ case DOWN_BEGIN:// 開始
case DOWN_FINISH:// 完毕
case DOWN_ERROR:// 失败 break;
case DOWN_UPDATA:// 更新进度条
msg.arg1 = factor;
break; default:
break;
}
msg.what = flag;
handler.sendMessage(msg);
} }

使用时简单说明下。

DownLoadHelper helper1 = new DownLoadHelper(this);
helper1.setUpdataView(tv1);
helper1.startDownLoad("http://img1.2345.com/appsimg/wallpaper/4/139460306960.jpg", path);

/********************************************/

Demo源代码下载地址

http://download.csdn.net/detail/jarlen/8552443

没有认真地检查。可能有bug,使用的伙伴请自己debug下。并通知我一下,谢谢

v=3&uin=791415371&site=qq&menu=yes">

基于Android 下载文件时,更新UI简单帮助类的更多相关文章

  1. 安卓下载文件怎样更新UI进度

    曾经写过几篇关于下载的文章.总的来说是下面几点: 1.维护一个下载进程的Hashmap,key:使用Md5进行处理后的文件下载地址,value为下载的Task. 以防止下载反复.并将信息保存至数据库. ...

  2. 下载文件时-修改文件名字 Redis在Windows中安装方法 SVN安装和使用(简单版) WinForm-SQL查询避免UI卡死 Asp.Net MVC Https设置

    下载文件时-修改文件名字   1后台代码 /// <summary> /// 文件下载2 /// </summary> /// <param name="Fil ...

  3. AsyncTask用法解析-下载文件动态更新进度条

    1. 泛型 AysncTask<Params, Progress, Result> Params:启动任务时传入的参数,通过调用asyncTask.execute(param)方法传入. ...

  4. 转载: 正确处理浏览器在下载文件时HTTP头的编码问题(Content-Disposition)

    最近在做一个下载工具时,发现CSDN上的资源下载时竟然没有被拦截到,经过分析,终于有了一个发现,解决了我之前做文件下载时的乱码问题,所以转载这篇释疑文章,希望有人可以看到,可以从中得到帮助,也用来备忘 ...

  5. Handler实现线程之间的通信-下载文件动态更新进度条

    1. 原理 每一个线程对应一个消息队列MessageQueue,实现线程之间的通信,可通过Handler对象将数据装进Message中,再将消息加入消息队列,而后线程会依次处理消息队列中的消息. 2. ...

  6. Android 下载文件及写入SD卡

    Android 下载文件及写入SD卡,实例代码 <?xml version="1.0" encoding="utf-8"?> <LinearL ...

  7. Firefox下载文件时中文名乱码问题

    为了形象化,先看几张不同浏览器下下载文件时的效果图: 1:Firefox 36.0.1 2:IE8 3:Chrome 40.0.2214.93 m 4:360 7.1.1.322 很明显在Firefo ...

  8. 使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法

    使用HttpURLConnection下载文件时经常会出现 java.io.FileNotFoundException文件找不到异常,下面介绍下解决办法 首先设置tomcat对get数据的编码:con ...

  9. 正确处理下载文件时HTTP头的编码问题(Content-Disposition)

    留坑 参考: 正确处理下载文件时HTTP头的编码问题(Content-Disposition) HTTP协议header中Content-Disposition中文文件名乱码 文件下载,content ...

随机推荐

  1. 暂停和屏蔽右键网页中的Flash

    如何暂停网页中的Flash?原理很简单,就是屏蔽Flash的消息即可.屏蔽右键也可以通过此方法 直接贴代码吧,加了注释,很容易就能懂了 新建工程,加一个WebBrowser,再加两个按钮.Flash ...

  2. [置顶] Oracle 11g Data Guard Role Transitions: Failover

    Role TransitionsInvolving Physical Standby Databases A database operates in one of the following mut ...

  3. Codeforces Round #235 (Div. 2) D. Roman and Numbers (数位dp、状态压缩)

    D. Roman and Numbers time limit per test 4 seconds memory limit per test 512 megabytes input standar ...

  4. vim高级编辑(一)

    本文出自   http://blog.csdn.net/shuangde800 ------------------------------------------------------------ ...

  5. [Oracle] 常用工具集之 - SQL*Loader

    SQL*Loader原理 SQL*Loader是Oracle提供的用于数据加载的一种工具,它比较适合业务分析类型数据库(数据仓库),能处理多种格式的平面文件,批量数据装载比传统的数据插入效率更高.其示 ...

  6. codeforces 659C Tanya and Toys

    题目链接:http://codeforces.com/problemset/problem/659/C 题意: n是已经有的数字,m是可用的最大数字和 要求选自己没有的数字,且这些数字的数字和不能超过 ...

  7. HP MSA2312 ERROR

    司在用的hp MAS2312存储其中一台每天都会报一个错误 EVENT:Vdisk verification failed. Command failed. (error code: 1) 2 err ...

  8. WOJ 1020

    #include<stdio.h> #include<stdlib.h> int main() { int n,m; int *num,*link; int i,j,t,k=0 ...

  9. 【IOS工具类】获得设备唯一标识(兼容IOS5,6,7)

    UIDevice+IdentifierAddition.h: #import <Foundation/Foundation.h> @interface UIDevice (Identifi ...

  10. js关闭浏览器窗口事件

    js关闭浏览器窗口 js关闭浏览器窗口,不弹出提示框.支持ie6+,火狐,谷歌等浏览器. <html> <head /> <body> <script typ ...