基于Android 下载文件时,更新UI简单帮助类
因为在项目开发时。有这种简单需求,问谷歌,网络上也有好多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下。并通知我一下,谢谢
基于Android 下载文件时,更新UI简单帮助类的更多相关文章
- 安卓下载文件怎样更新UI进度
曾经写过几篇关于下载的文章.总的来说是下面几点: 1.维护一个下载进程的Hashmap,key:使用Md5进行处理后的文件下载地址,value为下载的Task. 以防止下载反复.并将信息保存至数据库. ...
- 下载文件时-修改文件名字 Redis在Windows中安装方法 SVN安装和使用(简单版) WinForm-SQL查询避免UI卡死 Asp.Net MVC Https设置
下载文件时-修改文件名字 1后台代码 /// <summary> /// 文件下载2 /// </summary> /// <param name="Fil ...
- AsyncTask用法解析-下载文件动态更新进度条
1. 泛型 AysncTask<Params, Progress, Result> Params:启动任务时传入的参数,通过调用asyncTask.execute(param)方法传入. ...
- 转载: 正确处理浏览器在下载文件时HTTP头的编码问题(Content-Disposition)
最近在做一个下载工具时,发现CSDN上的资源下载时竟然没有被拦截到,经过分析,终于有了一个发现,解决了我之前做文件下载时的乱码问题,所以转载这篇释疑文章,希望有人可以看到,可以从中得到帮助,也用来备忘 ...
- Handler实现线程之间的通信-下载文件动态更新进度条
1. 原理 每一个线程对应一个消息队列MessageQueue,实现线程之间的通信,可通过Handler对象将数据装进Message中,再将消息加入消息队列,而后线程会依次处理消息队列中的消息. 2. ...
- Android 下载文件及写入SD卡
Android 下载文件及写入SD卡,实例代码 <?xml version="1.0" encoding="utf-8"?> <LinearL ...
- Firefox下载文件时中文名乱码问题
为了形象化,先看几张不同浏览器下下载文件时的效果图: 1:Firefox 36.0.1 2:IE8 3:Chrome 40.0.2214.93 m 4:360 7.1.1.322 很明显在Firefo ...
- 使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法
使用HttpURLConnection下载文件时经常会出现 java.io.FileNotFoundException文件找不到异常,下面介绍下解决办法 首先设置tomcat对get数据的编码:con ...
- 正确处理下载文件时HTTP头的编码问题(Content-Disposition)
留坑 参考: 正确处理下载文件时HTTP头的编码问题(Content-Disposition) HTTP协议header中Content-Disposition中文文件名乱码 文件下载,content ...
随机推荐
- HttpSession具体解释
session的机制 http是无状态的协议,客户每次读取web页面时,server都打开新的会话,并且server也不会自己主动维护客户的上下文信息,那么要怎么才干实现会话跟踪呢?session就是 ...
- hdu 4707 Pet 2013年ICPC热身赛A题 dfs水题
题意:linji的仓鼠丢了,他要找回仓鼠,他在房间0放了一块奶酪,按照抓鼠手册所说,这块奶酪可以吸引距离它D的仓鼠,但是仓鼠还是没有出现,现在给出一张关系图,表示各个房间的关系,相邻房间距离为1,而且 ...
- nginx源代码分析--模块分类
ngx-modules Nginx 基本的模块大致能够分为四类: handler – 协同完毕client请求的处理.产生响应数据.比方模块, ngx_http_rewrite_module, ngx ...
- 小米手机usb共享网络mac
今天.我想去FQgoogle,mac在墙上,不便于使用.甚至只是用Android手机wifi,打开墙软件.然后usb分享到mac.然后mac互联网. 在谈到一些复杂.其实,关键一,小米手机usb共享, ...
- 查看进程所用的内存(使用GetWindowThreadProcessId取得进程ID,OpenProcess打开进程和GetProcessMemoryInfo取得内存信息)
// function GetProcessMemorySize(_sProcessName: string; var _nMemSize: Cardinal): Boolean; var l_nWn ...
- WOJ 1020
#include<stdio.h> #include<stdlib.h> int main() { int n,m; int *num,*link; int i,j,t,k=0 ...
- 从零開始学android<Menu菜单组件.三十.>
在Android系统之中.菜单一共同拥有三类:选项菜单(OptionsMenu).上下文菜单(ContextMenu)和子菜单(SubMenu). 今天我们就用几个样例来分别介绍下菜单的使用 acti ...
- Company Story | Vistaprint
Company Story | Vistaprint Company Story A Gap in the Small Business Marketplace It’s rare that a hi ...
- python - ImportError: No module named http.cookies error when installing cherrypy 3.2 - Stack Overflow
python - ImportError: No module named http.cookies error when installing cherrypy 3.2 - Stack Overfl ...
- deque,list,queue,priority_queue
1.deque deque双端队列容器与vector一样,采用线性表顺序存储结构,但与vector唯一不同的是,deque采用分块的线性存储结构来存 储数据,每块的大小一般为512字节,称为一个deq ...