Android下载通用类
下面是整个帮助类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package sRoger.pack; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; public class DownLoad { private String strUrl = ""; private DownLoadCallBack mCallback = null; private MHandler mHandler = null; private Thread thread = null; private String fileName = ""; private int len = 0; // 下载文件总长度 private int total = 0; // 当前下载的长度 /** * 构造函数 * @param url URL */ public DownLoad(String url,String fileName,DownLoadCallBack callBack) { this.strUrl = url; this.mCallback = callBack; this.fileName = fileName; } /** * 下载文件 */ public void DownLoadFile() { mHandler = new MHandler(); thread = new Thread(runnable); thread.start(); } Runnable runnable = new Runnable() { @Override public void run() { try { URL url = new URL(strUrl); HttpURLConnection con = (HttpURLConnection)url.openConnection(); len = con.getContentLength(); SendMsg("maxLen", len); InputStream inStream = new BufferedInputStream(con.getInputStream()); String path = Environment.getExternalStorageDirectory().getAbsolutePath(); OutputStream outStream = new FileOutputStream(path + "/mMusic/"+fileName); byte[] buffer = new byte[10240]; int count = 0; total = 0; DecimalFormat format = new DecimalFormat("#0.00"); while((count = inStream.read(buffer)) != -1) { total += count; outStream.write(buffer,0,count); SendMsg("currentVal", total); double tLen = Double.valueOf(String.valueOf(len)); double tDownTotal = Double.valueOf(String.valueOf(total)); double tPercent = tDownTotal / tLen * 100; String tStrPercent = format.format(tPercent); SendMsg("percent", tStrPercent); } outStream.flush(); outStream.close(); inStream.close(); if(len == total) { SendMsg("success", 0); } else { SendMsg("error", -1); } } catch (Exception e) { e.printStackTrace(); } } }; final class MHandler extends Handler { public MHandler() { } public MHandler(Looper l) { super(l); } @Override public void handleMessage(Message msg) { try { super.handleMessage(msg); Bundle data = msg.getData(); if(data.containsKey("currentVal")) { int val = data.getInt("currentVal"); mCallback.UpdateUIProgress(val); } if(data.containsKey("maxLen")) { int val = data.getInt("maxLen"); mCallback.SetMaxProgress(val); } if(data.containsKey("percent")) { mCallback.ReturnPercent(data.getString("percent")); } if(data.containsKey("success")) { mCallback.Success(); StopThread(); } if(data.containsKey("error")) { mCallback.Error(); StopThread(); } } catch(Exception e) { StopThread(); } } } /** * 向Handler发送消息 * @param key 键 * @param val 值 */ private void SendMsg(String key,int val) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt(key, val); msg.setData(data); wl("-->"+key+val); mHandler.sendMessage(msg); } /** * 向Handler发送消息 * @param key 键 * @param val 值 */ private void SendMsg(String key,String val) { Message msg = new Message(); Bundle data = new Bundle(); data.putString(key, val+"%"); msg.setData(data); wl("-->"+key+val); mHandler.sendMessage(msg); } /** * 停止下载 */ public void StopThread() { if(thread != null) { Thread t = thread; thread = null; t.interrupt(); } wl("StopThread"); } /** * 写log * @param strLog */ private void wl(String strLog) { Log.i("sjr",strLog); } }
回调接口:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package sRoger.pack; /** * 下载回调接口 * @author SJR */ public interface DownLoadCallBack { /** * 更新进度条 */ void UpdateUIProgress(int cur); /** * 设置百分比 * @param percent 当前下载的百分比 */ void ReturnPercent(String percent); /** * 设置进度条最大值 * @param val */ void SetMaxProgress(int val); /** * 下载完成 */ void Success(); /** * 下载出错 */ void Error(); }
调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
String url = "http://zhangmenshiting5.baidu.com/data2/music/1837238/2460371341806461.mp3?xcode=74d240eb72f4e01b578f247b5baed415&lid=0"; DownLoad dl = new DownLoad(url,"xyzth.mp3", new CallBack()); dl.DownLoadFile();
实现回调接口:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * 回调接口的实现 * @author SJR */ final class CallBack implements DownLoadCallBack { @Override public void UpdateUIProgress(int cur) { setTitle("线程执行了"); sb.setProgress(cur); } @Override public void SetMaxProgress(int val) { sb.setMax(val); } @Override public void Success() { setTitle("下载完成!"); } @Override public void Error() { setTitle("下载出错!"); } @Override public void ReturnPercent(String percent) { tv_kb_state.setText(percent); } }
要想从网络上下载文件到本地内存卡上还要在AndroidManifest.xml中的<Application>节之前或之后添加以下配置内容:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
本博客内容,如需转载请务必保留超链接。Contact Me:Mail此处省略好几个字...