断点续传---多线程下载进阶(一)

打算总结7篇笔记。来学习下断点续传---多线程下载进阶

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sms.down"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MulThreadDownload"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <!-- 訪问 internet 权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

</manifest>

main.xml

<?

xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ProgressBar> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ProgressBar android:id="@+id/progressBar2" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ProgressBar> <TextView android:id="@+id/textView2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>


MulThreadDownload

package sms.down;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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.widget.ProgressBar;
import android.widget.TextView;

public class MulThreadDownload extends Activity {
	// 下载进度条1
	private ProgressBar pb1 = null;
	private TextView tv1 = null;
	// 下载进度条2
	private ProgressBar pb2 = null;
	private TextView tv2 = null;

	// 下载后存放的文件夹地址
	private final String root = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + File.separator;
	// 网络资源Url地址信息
	private final String downloadFile = "http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3";
	private final String downloadFile1 = "http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);

		this.pb1 = (ProgressBar) this.findViewById(R.id.progressBar1);
		this.tv1 = (TextView) this.findViewById(R.id.textView1);

		this.pb2 = (ProgressBar) this.findViewById(R.id.progressBar2);
		this.tv2 = (TextView) this.findViewById(R.id.textView2);

		this.download(this.downloadFile, this.root, this.pb1, this.tv1);

		this.download(this.downloadFile1, this.root, this.pb2, this.tv2);
	}

	/**
	 * 開始线程进行下载 參数:网络资源地址,存放的文件夹。进度条。提示的文本信息
	 */
	private void download(String url, String targetPath, ProgressBar pb,
			TextView tv) {
		DownloadThread dt = new DownloadThread(url, targetPath, pb, tv);
		dt.start();
	}

	// 自己定义一个Handler类。处理线程消息
	public class MyHandler extends Handler {
		private final ProgressBar progressBar;
		private final TextView textView;

		// 通过构造函数来确定给哪个ProgressBar刷新
		public MyHandler(ProgressBar progressBar, TextView textView) {
			this.progressBar = progressBar;
			this.textView = textView;
		}

		public void handleMessage(Message msg) {
			this.progressBar.setProgress(msg.arg1);
			this.textView.setText(msg.arg1 + "%");

			super.handleMessage(msg);
		}
	}

	// 下载线程
	public class DownloadThread extends Thread {
		private String url = "";
		private String targetPath = "";
		private ProgressBar pb = null;
		private TextView tv = null;

		public DownloadThread(String url, String targetPath, ProgressBar pb,
				TextView tv) {
			this.url = url;
			this.targetPath = targetPath;
			this.pb = pb;
			this.tv = tv;
			this.myHandler = new MyHandler(this.pb, this.tv);
		}

		// 初始化下载总大小为0
		private int hasDownload = 0;
		// 文件大小
		private int size = 0;
		// 下载比例
		private int rate = 0;
		// 读写流须要的
		private int len = -1;
		private final byte buffer[] = new byte[4 * 1024];

		private MyHandler myHandler = null;
		private Message msg = null;

		@Override
		public void run() {
			// http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3
			String targetFileName = this.targetPath
					+ this.url.substring(this.url.lastIndexOf("/") + 1,
							this.url.length());
			File downloadFile = new File(targetFileName);
			// 文件不存在。就进行创建工作
			if (!downloadFile.exists()) {
				try {
					downloadFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			try {
				// 获取URL地址
				URL fileUrl = new URL(this.url);
				// 打开连接
				HttpURLConnection conn = (HttpURLConnection) fileUrl
						.openConnection();
				// 获取文件大小
				this.size = conn.getContentLength();
				// 获取输入流
				InputStream is = conn.getInputStream();
				// 创建一个输出流
				OutputStream os = new FileOutputStream(targetFileName);

				while ((this.len = is.read(this.buffer)) != -1) {
					// write(byte[] buffer)
					os.write(this.buffer);
					// 通过循环读取的,进而改变下载量--更新下载进度
					this.hasDownload += this.len;
					// 获取下载比例
					this.rate = (this.hasDownload * 100 / this.size);
					// 创建消息对象
					this.msg = new Message();
					// 携带下载比例
					this.msg.arg1 = this.rate;
					// 发送消息
					this.myHandler.sendMessage(this.msg);

					System.out.println(this.rate + "%");
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}


原文地址:https://www.cnblogs.com/brucemengbm/p/7072707.html