您的位置:首页 > 理论基础 > 计算机网络

0913Android基础网络技术之下载(AsyncTask)

2015-09-15 07:49 615 查看

下载

  通过urlconnection以及线程实现下载

  下载之前要添加权限,以及在主线程中注册

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


  注册

<activity android:name=".MyDownloadActivity"></activity>


单线程下载

  通过继承AsyncTask新开一个线程,将下载过程中的数据用来设置progressbar

class MyAsynvTask extends AsyncTask<String,Integer,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int all=values[1];
int current=values[0];
int progress= (int) (current*100.0/all);
mProgressBar.setProgress(progress);
}

@Override
protected String doInBackground(String... params) {
try {
URL url=new URL("http://192.168.0.44:8080/MyServiceTest/music/aa.mp3");
URLConnection connection=url.openConnection();
int length=connection.getContentLength();
InputStream is=connection.getInputStream();
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"ee.mp3");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream os=new FileOutputStream(file);
byte[] array=new byte[1024];
int sum=0;
int index=is.read(array);
while (index!=-1){
os.write(array,0,index);
sum+=index;
publishProgress(sum,length);
index=is.read(array);
}
os.flush();
os.close();
is.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}


  启动线程

new MyAsynvTask().execute();


多线程下载

  新建线程类

package com.example.laowang.myinternet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* Created by Administrator on 2015/9/13.
*/
public class MultiThread extends Thread {

private int sum=0;
private long start;
private long end;
private String urlPath;
private String filePath;

public MultiThread(long start, long end, String url, String filePath) {
this.start = start;
this.end = end;
this.urlPath = url;
this.filePath = filePath;
}

public int getSum() {
return sum;
}

@Override
public void run() {
try {
URL url=new URL(urlPath);
URLConnection connection=url.openConnection();
//            如果为true,则允许进行用户交互(即下载前访问是否下载)
connection.setAllowUserInteraction(true);

connection.setRequestProperty("Range", "bytes=" + start + "-"
+ end);
InputStream is= connection.getInputStream();
byte [] array=new byte[1024];
//            is.read(array);
File file=new File(filePath);
//            RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了。
//              这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。
RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");
//            只有RandomAccessFile才有seek搜寻方法,而这个方法也只适用于文件
randomAccessFileile.seek(start);
int index=is.read(array);
while (index!=-1){
randomAccessFileile.write(array,0,index);
sum+=index;
index=is.read(array);
}
randomAccessFileile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


  在活动中运行线程

new Thread(new Runnable() {
@Override
public void run() {
try {
String urlPath="http://192.168.0.44:8080/MyServiceTest/music/aa.mp3";
URL  url = new URL(urlPath);
URLConnection connection=url.openConnection();
//                            获得文件的长度
length=connection.getContentLength();
//                            新建存放下载内容的文件。
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"dd.mp3");
if(!file.exists()){
file.createNewFile();
}

//                            新建多线程对象,打开五个线程同时进行下载。
MultiThread[] threads=new MultiThread[5];
for (int i=0;i<5;i++){
MultiThread thread=null;
//                                最后一部分,由于极大的可能没有正处,所有这边设置结束长度为文件的长度。
if(i==4){
thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
}else {
//                                 传入起始位置,结束位置,下载路径,下载文件存放路径。因为包前包后所以减一
thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());
}
thread.start();
threads[i]=thread;
}

//                          设置进度条
boolean isFinish=true;
while(isFinish){
int sum=0;
//                                获得五个线程的实时长度的和
for (MultiThread thread:threads){
sum+= thread.getSum();
}
Message msg=  handler.obtainMessage();
msg.what=0x23;
msg.arg1=sum;
handler.sendMessage(msg);
//
if(sum+10>=length){
isFinish=false;
}
Thread.sleep(1000);
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}).start();


单线程以及多线程下载运行gif

  达到的效果



全部代码

  活动

  

package com.example.laowang.myinternet;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* Created by Administrator on 2015/9/11.
*/
public class MyDownloadActivity extends Activity implements View.OnClickListener {
private Button mBtnSingelDownload;
private Button mBtnMulThreadDownload;
private ProgressBar mProgressBar;
int length;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x23:
//                    将进度条最大值设为文件最大值。
mProgressBar.setMax(length);
mProgressBar.setProgress(msg.arg1);
//                    mProgressBar.setProgress((int) (msg.arg1*100.0/length));
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);

mBtnSingelDownload = (Button) findViewById(R.id.button_signal_thread_download);
mBtnMulThreadDownload = (Button) findViewById(R.id.button_mul_thread_download);
mProgressBar= (ProgressBar) findViewById(R.id.progressBar);

mBtnSingelDownload.setOnClickListener(this);
mBtnMulThreadDownload.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_signal_thread_download:
new MyAsynvTask().execute();
break;
case R.id.button_mul_thread_download:
new Thread(new Runnable() {
@Override
public void run() {
try {
String urlPath="http://192.168.0.44:8080/MyServiceTest/music/aa.mp3";
URL  url = new URL(urlPath);
URLConnection connection=url.openConnection();
//                            获得文件的长度
length=connection.getContentLength();
//                            新建存放下载内容的文件。
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"dd.mp3");
if(!file.exists()){
file.createNewFile();
}

//                            新建多线程对象,打开五个线程同时进行下载。
MultiThread[] threads=new MultiThread[5];
for (int i=0;i<5;i++){
MultiThread thread=null;
//                                最后一部分,由于极大的可能没有正处,所有这边设置结束长度为文件的长度。
if(i==4){
thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
}else {
//                                 传入起始位置,结束位置,下载路径,下载文件存放路径。因为包前包后所以减一
thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());
}
thread.start();
threads[i]=thread;
}

//                          设置进度条
boolean isFinish=true;
while(isFinish){
int sum=0;
//                                获得五个线程的实时长度的和
for (MultiThread thread:threads){
sum+= thread.getSum();
}
Message msg=  handler.obtainMessage();
msg.what=0x23;
msg.arg1=sum;
handler.sendMessage(msg);
//
if(sum+10>=length){
isFinish=false;
}
Thread.sleep(1000);
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}).start();
break;
default:
break;
}
}

class MyAsynvTask extends AsyncTask<String,Integer,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int all=values[1];
int current=values[0];
int progress= (int) (current*100.0/all);
mProgressBar.setProgress(progress);
}

@Override
protected String doInBackground(String... params) {
try {
URL url=new URL("http://192.168.0.44:8080/MyServiceTest/music/aa.mp3");
URLConnection connection=url.openConnection();
int length=connection.getContentLength();
InputStream is=connection.getInputStream();
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"ee.mp3");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream os=new FileOutputStream(file);
byte[] array=new byte[1024];
int sum=0;
int index=is.read(array);
while (index!=-1){
os.write(array,0,index);
sum+=index;
publishProgress(sum,length);
index=is.read(array);
}
os.flush();
os.close();
is.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}


  多线程下载新开的线程类

package com.example.laowang.myinternet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* Created by Administrator on 2015/9/13.
*/
public class MultiThread extends Thread {

private int sum=0;
private long start;
private long end;
private String urlPath;
private String filePath;

public MultiThread(long start, long end, String url, String filePath) {
this.start = start;
this.end = end;
this.urlPath = url;
this.filePath = filePath;
}

public int getSum() {
return sum;
}

@Override
public void run() {
try {
URL url=new URL(urlPath);
URLConnection connection=url.openConnection();
//            如果为true,则允许进行用户交互(即下载前访问是否下载)
connection.setAllowUserInteraction(true);

connection.setRequestProperty("Range", "bytes=" + start + "-"
+ end);
InputStream is= connection.getInputStream();
byte [] array=new byte[1024];
//            is.read(array);
File file=new File(filePath);
//            RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了。
//              这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。
RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");
//            只有RandomAccessFile才有seek搜寻方法,而这个方法也只适用于文件
randomAccessFileile.seek(start);
int index=is.read(array);
while (index!=-1){
randomAccessFileile.write(array,0,index);
sum+=index;
index=is.read(array);
}
randomAccessFileile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


  布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/button_mul_thread_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="多线程下载" />
<Button
android:id="@+id/button_signal_thread_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="单线程下载" />

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络 线程 下载