本文实例为大家分享了AndroID实现断点续传和下载的具体代码,供大家参考,具体内容如下
效果展示
导入依赖与权限
依赖
compile 'com.loopj.androID:androID-async-http:1.4.9'
权限
<uses-permission androID:name="androID.permission.INTERNET"></uses-permission> <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE"></uses-permission>
主MainActivity(布局)
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:ID="@+ID/activity_main" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:paddingBottom="@dimen/activity_vertical_margin" androID:paddingleft="@dimen/activity_horizontal_margin" androID:paddingRight="@dimen/activity_horizontal_margin" androID:paddingtop="@dimen/activity_vertical_margin" tools:context="com.lv.mama.test004.MainActivity"> <Progressbar androID:layout_wIDth="match_parent" androID:layout_height="20dp" androID:layout_margintop="15dp" androID:ID="@+ID/pb" androID:layout_alignParenttop="true" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" /> <TextVIEw androID:text="TextVIEw" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_below="@+ID/pb" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_marginleft="20dp" androID:layout_marginStart="20dp" androID:layout_margintop="13dp" androID:ID="@+ID/tv_info" /> <button androID:text="暂停" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_margintop="17dp" androID:ID="@+ID/bt_pause" androID:onClick="pause" androID:layout_below="@+ID/tv_info" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_marginleft="11dp" androID:layout_marginStart="11dp" /> <button androID:text="开始" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_marginRight="24dp" androID:layout_marginEnd="24dp" androID:ID="@+ID/bt_download" androID:onClick="download" androID:layout_alignBaseline="@+ID/bt_pause" androID:layout_alignBottom="@+ID/bt_pause" androID:layout_alignParentRight="true" androID:layout_alignParentEnd="true" /></relativeLayout>
主MainActivity
public class MainActivity extends AppCompatActivity { protected static final String TAG = "OtherActivity"; //下载线程的数量 private final static int threadsize = 3; protected static final int SET_MAX = 0; public static final int UPDATE_VIEW = 1; private Progressbar pb; private button bt_download; private button bt_pause; private TextVIEw tv_info; //显示进度和更新进度 private Handler mHandler = new Handler() { public voID handleMessage(androID.os.Message msg) { switch (msg.what) { case SET_MAX://设置进度条的最大值 int filelength = msg.arg1; pb.setMax(filelength); break; case UPDATE_VIEW://更新进度条 和 下载的比率 int len = msg.arg1;//新下载的长度 pb.setProgress(pb.getProgress() + len);//设置进度条的刻度 int max = pb.getMax();//获取进度的最大值 int progress = pb.getProgress();//获取已经下载的数据量 // 下载:30 总:100 int result = (progress * 100) / max; tv_info.setText("下载:" + result + "%"); break; default: break; } } ; }; String uri = "http://c.hiphotos.baIDu.com/image/pic/item/b90e7bec54e736d1e51217c292504fc2d46269f3.jpg"; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); //找到控件 pb = (Progressbar) findVIEwByID(R.ID.pb); tv_info = (TextVIEw) findVIEwByID(R.ID.tv_info); bt_download = (button) findVIEwByID(R.ID.bt_download); bt_pause = (button) findVIEwByID(R.ID.bt_pause); //数据的回显 //确定下载的文件 String name = getfilename(uri); file file = new file(Environment.getExternalStorageDirectory(),name); if (file.exists()) {//文件存在回显 //获取文件的大小 int filelength = (int) file.length(); pb.setMax(filelength); try { //统计原来所有的下载量 int count = 0; //读取下载记录文件 for (int threadID = 0; threadID < threadsize; threadID++) { //获取原来指定线程的下载记录 int existDownloadLength = readDownloadInfo(threadID); count = count + existDownloadLength; } //设置进度条的刻度 pb.setProgress(count); //计算比率 int result = (count * 100) / filelength; tv_info.setText("下载:" + result + "%"); } catch (Exception e) { e.printstacktrace(); } } } //暂停 private boolean flag = false;//是否在下载 public voID pause(VIEw v){ flag = false; bt_download.setEnabled(true); bt_pause.setEnabled(false); } //下载 public voID download(VIEw v){ flag = true; //是在下载 bt_download.setEnabled(false);//一点击变成不可点击 bt_pause.setEnabled(true);//一点击变成可点击 new Thread(){//子线程 public voID run() { try { //获取服务器上文件的大小 httpClIEnt clIEnt = new DefaulthttpClIEnt(); httphead request = new httphead(uri); httpResponse response = clIEnt.execute(request); //response 只有响应头 没有响应体 if(response.getStatusline().getStatusCode() == 200){ header[] headers = response.getheaders("Content-Length"); String value = headers[0].getValue(); //文件大小 int filelength = Integer.parseInt(value); Log.i(TAG,"filelength:"+filelength); //设置进度条的最大值 Message msg_setmax = Message.obtain(mHandler,SET_MAX,filelength,0); msg_setmax.sendToTarget(); //处理下载记录文件 for(int threadID=0;threadID<threadsize;threadID++){ //对应的下载记录文件 file file = new file(Environment.getExternalStorageDirectory(),threadID+".txt"); //判断文件是否存在 if(!file.exists()){ //创建文件 file.createNewfile(); } } //在sdcard创建和服务器大小一样的文件 String name = getfilename(uri); file file = new file(Environment.getExternalStorageDirectory(),name); //随机访问文件 RandomAccessfile raf = new RandomAccessfile(file,"rwd"); //设置文件的大小 raf.setLength(filelength); //关闭 raf.close(); //计算每条线程的下载量 int block = (filelength%threadsize == 0)?(filelength/threadsize):(filelength/threadsize+1); //开启三条线程执行下载 for(int threadID=0;threadID<threadsize;threadID++){ new DownloadThread(threadID,uri,file,block).start(); } } } catch (Exception e) { e.printstacktrace(); } }; }.start(); } //线程下载类 private class DownloadThread extends Thread { private int threadID;//线程的ID private String uri;//下载的地址 private file file;//下载文件 private int block;//下载的块 private int start; private int end; public DownloadThread(int threadID,String uri,file file,int block) { super(); this.threadID = threadID; this.uri = uri; this.file = file; this.block = block; //计算下载的开始位置和结束位置 start = threadID * block; end = (threadID + 1) * block - 1; try { //读取该条线程原来的下载记录 int existDownloadLength = readDownloadInfo(threadID); //修改下载的开始位置 从新下载 start = start + existDownloadLength; } catch (Exception e) { e.printstacktrace(); } } //下载 状态码:200是普通的下载 206是分段下载 Range:范围 @OverrIDe public voID run() { super.run(); try { RandomAccessfile raf = new RandomAccessfile(file,"rwd"); //跳转到起始位置 raf.seek(start); //分段下载 httpClIEnt clIEnt = new DefaulthttpClIEnt(); httpGet request = new httpGet(uri); request.addheader("Range","bytes:"+start+"-"+end);//添加请求头 httpResponse response = clIEnt.execute(request); if(response.getStatusline().getStatusCode() == 200){ inputStream inputStream = response.getEntity().getContent(); //把流写入到文件 byte[] buffer = new byte[1024]; int len = 0; while((len = inputStream.read(buffer)) != -1){ //如果暂停下载 点击暂停 false 就直接return 点击下载true接着下载 if(!flag){ return;//标准线程结束 } //写数据 raf.write(buffer,len); //读取原来下载的数据量 这里读取是为了更新下载记录 int existDownloadLength = readDownloadInfo(threadID);//原来下载的数据量 //计算最新的下载 int newDownloadLength = existDownloadLength + len; //更新下载记录 从新记录最新下载位置 updateDownloadInfo(threadID,newDownloadLength); //更新进度条的显示 下载的百分比 Message update_msg = Message.obtain(mHandler,UPDATE_VIEW,len,0); update_msg.sendToTarget(); //模拟 看到进度条动的效果 SystemClock.sleep(50); } inputStream.close(); raf.close(); Log.i(TAG,"第"+threadID+"条线程下载完成"); } } catch (Exception e) { e.printstacktrace(); } } } /** * 读取指定线程的下载数据量 * @param threadID 线程的ID * @return * @throws Exception */ public int readDownloadInfo(int threadID) throws Exception{ //下载记录文件 file file = new file(Environment.getExternalStorageDirectory(),threadID+".txt"); BufferedReader br = new BufferedReader(new fileReader(file)); //读取一行数据 String content = br.readline(); int downlength = 0; //如果该文件第一次创建去执行读取 *** 作 文件里面的内容是 null if(!TextUtils.isEmpty(content)){ downlength = Integer.parseInt(content); } //关闭流 br.close(); return downlength; } /** * 更新下载记录 * @param threadID * @param newDownloadLength */ public voID updateDownloadInfo(int threadID,int newDownloadLength) throws Exception{ //下载记录文件 file file = new file(Environment.getExternalStorageDirectory(),threadID+".txt"); fileWriter fw = new fileWriter(file); fw.write(newDownloadLength+""); fw.close(); } /** * 获取文件的名称 * @param uri * @return */ private String getfilename(String uri){ return uri.substring(uri.lastIndexOf("/")+1); }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android实现简单断点续传和下载到本地功能全部内容,希望文章能够帮你解决Android实现简单断点续传和下载到本地功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)