基于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 ...
随机推荐
- Webbrowser加载Flash后方向键失效问题(用到了OLE接口,没有被处理就转发,够复杂的)
原文:http://blog.csdn.net/dropme/article/details/6253528 窗体上放一个ApplicationEvent控件,OnMessage事件中这么写 uses ...
- 【MongoDB】学习MongoDB推荐三本书
近期学习mongodb,感觉这三本书写得不错.非常大家分享一下:
- Android监听外部存储设备的状态(SD卡、U盘等等)
近期在项目中须要对外部存储设备的状态进行监听,所以整理了此笔记,以便日后查看. 外部存储设备的状态变化时发出的广播 对照不同状态下的广播 1. 插入外部SD卡时: 2. 移除外部SD卡时: 3. 连接 ...
- A*寻路算法的实现
原理:http://www.cppblog.com/christanxw/archive/2006/04/07/5126.html 算法理论请到原理这个传送门,代码中的注释,已经比较详细,所以我不会讲 ...
- SharePoint场管理-PowerShell(二)
1. 合并Log文件 Merge-SPLogFile –Path E:\Logs\MergedLog.log –StartTime "1/19/2010" –Overwrite 2 ...
- ANSI C中取得结构体字段偏移量的常用方法
来自http://blog.chinaunix.net/u2/62910/showart_492571.html 假设在ANSI C程序中定义了一个名为MyStruct的结构类型,其中有一个名为MyF ...
- 使用PageHeap.EXE或GFlags.EXE检查内存越界错误
必先利其器之一:使用PageHeap.EXE或GFlags.EXE检查内存越界错误 Article last modified on 2002-6-3 ------------------------ ...
- 利用用户自己的server、tomcat下的解决iOS7.1企业应用无法安装应用程序 由于证书无效的问题
1.环境 )操作系统:Windows server 2003.Windows server2008 )JDK:jdk 1.6 )apache-tomcat-6.0.35(注意版本号号,版本号6.0.1 ...
- Keywords Search (ac 自己主动机)
Keywords Search Problem Description In the modern time, Search engine came into the life of everybod ...
- ubuntu12 环境下编译freerdp
有时候需要从linux环境下远程连接到windows的环境,可以采用freerdp.freerdp是一个linux下开源的工具,在Ubuntu下可以直接用 apt-get install freerd ...