android multi_thread多线程下载

MainActivity.java

package com.multi_thread.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private Button btn_download;
private ProgressBar progressBar;
private MyHandler myHandler;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn_download = (Button) findViewById(R.id.button1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setProgress(0);

btn_download.setOnClickListener(this);
myHandler = new MyHandler();
}

@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
MyThread thread = new MyThread();
thread.start();
}
}

class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();

Toast.makeText(MainActivity.this, bundle.get("name").toString(),
Toast.LENGTH_SHORT).show();
}

}

class MyThread extends Thread {
@Override
public void run() {
callHandler("开始下载");
progressBar.setProgress(0);
try {
URL url = new URL(
"http://192.168.43.78:8080/MyWeb/only_one_sing.mp3");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int filesize = connection.getContentLength();
progressBar.setMax(filesize);
InputStream input = connection.getInputStream();
File file = new File(Environment.getExternalStorageDirectory()
+ "/aaa/aa.mp3");// Environment.getExternalStorageDirectory()
file.createNewFile();
OutputStream output = new FileOutputStream(file);
byte[] b = new byte[1024];

int fenzise = filesize / 2;
int sizemore = filesize % 2;

MultiThread[] threads = new MultiThread[2];
for (int i = 0; i < threads.length; i++) {
MultiThread thread = new MultiThread(url, file, i*fenzise, fenzise
* (i + 1) - 1);
thread.start();
threads[i] = thread;
}
int count=0;
boolean isfinished = true;
while (isfinished) {
// 先把整除的余数搞定
count = sizemore;
isfinished = false;
for (int i = 0; i < threads.length; i++) {
count += threads[i].getDownloadsize();
if (!threads[i].isOk()) {
isfinished = true;
}
}
progressBar.setProgress(count);//更新下载进度
// 休息1秒后再读取下载进度
if(count==filesize){
callHandler("下载结束");
System.out.println("---------下载结束");
}
sleep(1000);
}

} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

// 调用Handler
private void callHandler(String str) {
// TODO Auto-generated method stub
Message message = new Message();
Bundle data = new Bundle();
data.putString("name", str);
message.setData(data);
MainActivity.this.myHandler.sendMessage(message);
}
}
}

MultiThread.java

package com.multi_thread.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;

public class MultiThread extends Thread{

private URL url;
private File file;
private int startPsittion;
private int endPosition;
private boolean isOk=false;// 用于标识当前线程是否下载完成

private int downloadsize;

public MultiThread(URL url,File file,int startPsittion,int endPosition) {
this.url=url;
this.file=file;
this.startPsittion=startPsittion;
this.endPosition=endPosition;
}

@Override
public void run() {
try {
BufferedInputStream input=null;
RandomAccessFile output=null;
byte[] b=new byte[1024];
URLConnection conn=url.openConnection();
conn.setAllowUserInteraction(true);

// 设置当前线程下载的起点,终点
conn.setRequestProperty("Range","bytes="+startPsittion+"-"+endPosition);
// 使用java中的RandomAccessFile 对文件进行随机读写操作
output=new RandomAccessFile(file, "rw");
// 设置开始写文件的位置
output.seek(startPsittion);

input=new BufferedInputStream(conn.getInputStream());
int count=0;
// 开始循环以流的形式读写文件
while(count<endPosition){
int length=input.read(b, 0, 1024);
if(length==-1)
break;

output.write(b,0,length);//错误代码:output.write(b,0,1024);
count+=length;

if(count>endPosition){
downloadsize+=length-(count-endPosition)+1;
}else{
downloadsize+=length;
}
}
isOk=true;// 下载完成设为true
input.close();
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public boolean isOk() {
return isOk;
}

public int getDownloadsize() {
return downloadsize;
}


}


activity_main.xml

<RelativeLayout 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" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="100dp"
android:text="下载" />

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="10dp"
android:layout_below="@+id/button1" />

</RelativeLayout>

manifest.xml

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个android平台上的 扩展任务库,在AsyncTask基础上进行扩展。 用法 1.继承 com.github.snowdream.android.util.concurrent.AsyncTask //inherit a class from com.github.snowdream.android.util.concurrent.AsyncTask public class DownloadFilesTask extends AsyncTask { public DownloadFilesTask(TaskListener listener) { //explicit inherit the construction from the super class. super(listener); } /** * TODO * if error occurs,carry it out. * * if (listener != null) { * listener.onError(new Throwable()); * } */ protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i ) { totalSize = 10; publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return totalSize; } } 2.定义一个 TaskListener.其中的第一个泛型参数是返回结果类型,第二个泛型参数是任务进度的类型。 private TaskListener listener = new TaskListener(){ @Override public void onStart() { super.onStart(); Log.i("onStart()"); } @Override public void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); Log.i("onProgressUpdate(values)" values[0] ); } @Override public void onSuccess(Long result) { super.onSuccess(result); Log.i("onSuccess(result)" result); } @Override public void onCancelled() { super.onCancelled(); Log.i("onCancelled()"); } @Override public void onError(Throwable thr) { super.onError(thr); Log.i("onError()"); } @Override public void onFinish() { super.onFinish(); Log.i("onFinish()"); } }; 3.创建一个AsyncTask任务,并且执行。 URL url = null; try { url = new URL("http://www.baidu.com/"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } new DownloadFilesTask(listener).execute(url,url,url); 标签:android
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值