最近刚学了安卓的下载,为了日后方便复习,就来一个总结吧。
下载的第一种方式:创建一个子线程,通过访问网络的方式下载数据。
关键步骤及代码如下:
1.在手机端sd卡中创建一个和需要下载的文件相同数据类型和大小的临时文件,来保存下载的数据
int length=conn.getContentLength();
RandomAccessFile raf=new RandomAccessFile(Environment.getExternalStorageDirectory() +"/temp.exe","rw");
raf.setLength(length);
2.设置多线程的个数
private static int ThreanCount=3;
3.设置每个线程下载大小
int blocksize=length/ThreanCount;
4.设置每个线程下载开始的地方和结束的地方
for(int threadid=0;threadid
{
startindex=threadid*blocksize; // 下载开始的地方
endindex=(threadid+1)*blocksize-1;//下载结束的地方
if(threadid==ThreanCount-1)
{
endindex=length-1;
}
5.在子线程中执行下载
new DownThread(path,threadid,startindex,endindex).start();
子线程代码:
public class DownThread extends Thread{
String path;
int threadid;
int startindex;
int endindex;
public DownThread(String path, int threadid, int startindex, int endindex) {
super();
this.path = path;
this.threadid = threadid;
this.startindex = startindex;
this.endindex = endindex;
}
public void run(){
try {
//设置路径,开始下载
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//设置请求的数据范围
conn.setRequestProperty("Range", "bytes="+startindex+"-"+endindex);
conn.setRequestMethod("POST");//设置请求方式
conn.setReadTimeout(3000);//设置超时时间
int type=conn.getResponseCode();//获取响应码
if(type==206)
{
InputStream is=conn.getInputStream();
RandomAccessFile raf=new RandomAccessFile("temp.exe", "rw");
//从指定的位置开始写数据
raf.seek(startindex);
byte[] buffer=new byte[1024];
int len=-1;
while((len=is.read(buffer))!=-1)
{
raf.write(buffer,0,len);
}
raf.close();
is.close();
System.out.println("线程"+threadid+"下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种方式:利用开源框架XUtils执行下载
步骤及代码:
1.导入XUtils的jar包
2.实例化HttpUtils对象
HttpUtils hu=new HttpUtils();
3.调用download方法执行下载
hu.download(path,Environment.getExternalStorageDirectory()+"/temp.exe",new RequestCallBack() {
@Override
public void onSuccess(ResponseInfo response) {
Toast.makeText(MainActivity.this, "文件下载,保存在"+response.result.getPath(), 0).show();
}
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(MainActivity.this, "文件失败", 0).show();
}
});