您的位置:首页 > 移动开发 > Android开发

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();
}

}
}
}


最后;别忘了把权限加上哦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: