android中之断点续传
2015-11-18 17:18
573 查看
此源码有助于理解;也是参照网上大神案例来改写的
源代码贴上
最后;别忘了把权限加上哦
源代码贴上
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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=".MainActivity" android:orientation="vertical" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始下载" android:onClick="click" /> <ProgressBar android:id="@+id/pb" android:layout_width="match_parent" android:layout_height="wrap_content" style="@android:style/Widget.ProgressBar.Horizontal" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package com.xm.download; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends Activity { final String path="http://gdown.baidu.com/data/wisegame/775ed200394c4c3d/QQyinle_283.apk"; final String pathName="QQyinle_283.apk"; final int ThreadCount=3; static int finishedThread; int currentProgress; private ProgressBar pb; TextView tv; Handler handler=new Handler() { @Override public void handleMessage(Message msg) { if(msg.what==1) { //把变量改成long,在long下运算 tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb=(ProgressBar)findViewById(R.id.pb); tv=(TextView)findViewById(R.id.tv); } /** * * @param v */ public void click(View v) { Thread ad=new Thread() { @Override public void run() { //发送get请求 try { URL url=new URL(path); HttpURLConnection huc=(HttpURLConnection)url.openConnection(); huc.setRequestMethod("GET"); huc.setConnectTimeout(5000); huc.setReadTimeout(5000); if(huc.getResponseCode()==200)//请求成功 { int contentLenth=huc.getContentLength();//得到长度 //设置进度条的最大长度为文件的长度 pb.setMax(contentLenth); //生成临时文件 File file=new File(Environment.getExternalStorageDirectory(),pathName); RandomAccessFile raf=new RandomAccessFile(file,"rwd"); raf.setLength(contentLenth);//设置大小 raf.close(); //计算出每个区间的下载大小 int size=contentLenth/ThreadCount; for(int i=0;i<ThreadCount;i++) { int startIndex=i*size; int endIndex=(i+1)*size-1; if(i==ThreadCount-1)//如果为最后一个 { endIndex=contentLenth-1; } new DownLoadThread(startIndex,endIndex,i).start(); } } } catch (Exception e) { e.printStackTrace(); } } }; ad.start(); } class DownLoadThread extends Thread { int startIndex; int endIndex; int threadId; public DownLoadThread(int startIndex, int endIndex, int threadId) { this.startIndex = startIndex; this.endIndex = endIndex; this.threadId = threadId; } @Override public void run() { try { File fileRaf=new File(Environment.getExternalStorageDirectory(),threadId+".txt"); if(fileRaf.exists()) { FileInputStream isfile=new FileInputStream(fileRaf); BufferedReader br=new BufferedReader(new InputStreamReader(isfile)); int parseInt = Integer.parseInt(br.readLine()); startIndex+=parseInt; //把上次下载位置显示至进度条 currentProgress+=parseInt; //发送消息;让主线程刷新进度条 handler.sendEmptyMessage(1); isfile.close(); br.close(); } URL url=new URL(path); HttpURLConnection huc=(HttpURLConnection)url.openConnection(); huc.setRequestMethod("GET"); huc.setConnectTimeout(5000); huc.setReadTimeout(5000); //设置本次http请求所请求的数据的区间 huc.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex); if(huc.getResponseCode()==206) { InputStream is = huc.getInputStream(); //拿到临时文件的输入流 File file=new File(Environment.getExternalStorageDirectory(),pathName); RandomAccessFile raf=new RandomAccessFile(file,"rwd"); raf.seek(startIndex);//设置文件写入位置 byte[] b=new byte[1024]; int len=0; int total=0; while((len=is.read(b))!=-1) { raf.write(b,0, len); total+=len; System.out.println("线程"+threadId+"下载了"+total); currentProgress+=len; pb.setProgress(currentProgress); handler.sendEmptyMessage(1); //进度写入文件中 RandomAccessFile rafile=new RandomAccessFile(fileRaf,"rwd"); rafile.write((total+"").getBytes()); rafile.close(); } raf.close(); is.close(); finishedThread++;//删除保存进度文件 synchronized (path) { if (finishedThread == ThreadCount) { for (int i = 0; i < ThreadCount; i++) { File f = new File(Environment.getExternalStorageDirectory(), i + ".txt"); f.delete(); } System.out.println("下载完成"); finishedThread = 0;// } } } } catch (Exception e) { e.printStackTrace(); } } } }
最后;别忘了把权限加上哦
相关文章推荐
- Android自定义手势识别
- 【Android学习笔记】Broadcast receiver
- android进行录音功能并保存播放
- Android控件之Service AIDL实现机制demo
- Android 如果布局中有ScrollView和Fragment或者带有滚动条的布局进行嵌套,布局加载完成页面无法定位到顶部的情况
- WINDOWS7环境下android studio、NDK配置补充
- Android过渡动画之进入退出
- 关于图片加载优化的小技巧
- android在java代码中动态添加组件及相关布局方法(LayoutParams)
- Android中的Service的用法 开启服务,下一篇讲绑定服务
- Android 音效流程分析
- Android开发之Android Material Design Toolbar自定义随笔
- Android Service小记
- Android Studio Prettify 插件
- android获取view宽高的几种方法,解决获取高宽为0问题
- Android fragment源码全解析
- AndroidSwipeLayout源码
- Android下开机自启动C程序
- Android Menu:使用Popup Menu
- android listview 滚动到底部