当前位置:首页 > 开发 > 编程语言 > 多线程 > 正文

android multi_thread多线程下载

发表于: 2014-06-12   作者:baoyao   来源:转载   浏览次数:
摘要: 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.HttpURLC
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"/>



android multi_thread多线程下载

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
要是先多线程下载,则必须对同一个文件可任意位置的写入 ,java中提供这样一个类可任意写入RandomAc
Android中级篇之多线程下载 2011-06-05 15:50:49 要是先多线程下载,则必须对同一个文件可任意位置
Android中级篇之多线程下载 2011-06-05 15:50:49 要是先多线程下载,则必须对同一个文件可任意位置
文章来源:http://www.itnose.net/detail/6051823.html 更多文章:http://www.itnose.net/type/85.h
本示例介绍在Android平台下通过HTTP协议实现断点续传下载。 我们编写的是Andorid的HTTP协议多线程断
本文转自:http://www.cnblogs.com/hanyonglu/archive/2012/02/20/2358801.html 本示例介绍在Androi
使用多线程断点续传下载器在下载的时候多个线程并发可以占用服务器端更多资源,从而加快下载速度,
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/26994463 有个朋友需要个多线
在Android中一个常见的、经常会遇到的需求是:用户的行为(如登录或下载图片)触发了到服务器端的数
本示例介绍在Android平台下通过HTTP协议实现断点续传下载。 我们编写的是Andorid的HTTP协议多线程断
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号