android 之断点续传详解三部曲之[一] → 多任务下载

简介: <p style="color:rgb(54,46,43); line-height:26px; padding-top:0px; padding-bottom:0px; margin-top:1em; margin-bottom:0.5em"> <span style="font-family:Microsoft YaHei; font-size:18px"><span style="

项目需求,需要做一个下载功能,当然理想的功能要支持多任务同时下载,断点续传的功能,我想一步一步来,首先困难摆在了多任务这里

开始我的思路是在一个Service中启动下载的流操作,然后通过Service中声明一个Activity中的Handler更新UI(比如进度条。。。)

可是我发现在Service中声明一个Activity中的Handler是做不到的(可能只是我做不到吧,无法申请内存)

于是,我决定在Activity中直接启动线程,让其运行,调用自身的Handler来更新UI,没想到在这个下载Activity onPause()的时候,线程还是活的,也就是说可以继续下载,下例是我做的一个两个任务同时下载的小例子,后面会把理想中的功能都陆续添加上的。。。。。。

首先是布局文件,这个没什么,贴上代码:

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>

然后是配置文件,上代码:

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>

下面就是实现代码,代码中有相应的注释:

MulThreadDownload.java

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 {

	/** Called when the activity is first created. */
	private ProgressBar pb1 = null;
	private TextView tv1 = null;
	private ProgressBar pb2 = null;
	private TextView tv2 = null;

	private final String root = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
	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 int hasDownload = 0;

		private int len = -1;
		private final byte buffer[] = new byte[4 * 1024];
		private int size = 0;
		private int rate = 0;

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

		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);
		}

		public void run() {
			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 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) {
					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();
			}

		}
	}

}

MyThreadTest.java

package sms.down;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MyThreadTest extends Activity {

	private ProgressBar pb1 = null;
	private TextView tv1 = null;
	private Handler handler = null;

	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);
		handler = new Handler() {
			public void handleMessage(Message msg) {

				pb1.setProgress(msg.arg1);
				tv1.setText(msg.arg1 + "%");
				switch (msg.arg1) {
				case 100:
					tv1.setText("下载完成!!");
					break;
				}

				super.handleMessage(msg);
			}

		};

		Runnable runnable = new Runnable() {
			int i = 0;

			public void run() {
				while (i != 100) {
					i = i + 10;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Message message = new Message();
					message.arg1 = i;
					handler.sendMessage(message);
				}
			}

		};
		new Thread(runnable).start();
	}
}

下面上一张真机效果图:



源码下载地址:http://download.csdn.net/detail/gulaer/5004954  源码中包含"android 之断点续传详解三部曲之[二] → 断点续传下载"和"android 之断点续传详解三部曲之[三] → 多任务同时下载"代码.

原文地址:http://blog.csdn.net/shimiso/article/details/6763986 非常感谢原作者.

相关文章
|
4月前
|
开发工具 Android开发 开发者
Android Studio详细下载,安装使用教程
Android Studio详细下载,安装使用教程
297 0
|
4月前
|
XML Java Android开发
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
130 0
|
4月前
|
XML Java Android开发
Android Studio App开发之捕获屏幕的变更事件实战(包括竖屏与横屏切换,回到桌面与切换到任务列表)
Android Studio App开发之捕获屏幕的变更事件实战(包括竖屏与横屏切换,回到桌面与切换到任务列表)
38 0
|
1月前
|
Shell 开发工具 Android开发
ADB 下载、安装及使用教程:让你更好地管理 Android 设备
ADB 下载、安装及使用教程:让你更好地管理 Android 设备
451 2
|
1月前
|
Android开发 对象存储
OSS对象储存android开发进行下载到本地文件时异步操作失效
android vivo80使用官方示例代码进行文件下载,但是使用oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>()时onSuccess和onFailure不执行
|
4月前
|
XML Java 调度
Android App网络通信中通过runOnUiThread快速操纵界面以及利用线程池Executor调度异步任务实战(附源码 简单易懂)
Android App网络通信中通过runOnUiThread快速操纵界面以及利用线程池Executor调度异步任务实战(附源码 简单易懂)
30 0
|
4月前
|
XML Java Android开发
Android Studio App开发之下载管理器DownloadManager中显示、轮询下载进度、利用POST上传文件讲解及实战(附源码)
Android Studio App开发之下载管理器DownloadManager中显示、轮询下载进度、利用POST上传文件讲解及实战(附源码)
93 0
|
4月前
|
XML Java Android开发
Android Studio App开发中异步任务AsynTask与异步服务IntentService的讲解与实战(实现四大名著的加载进度条 附源码)
Android Studio App开发中异步任务AsynTask与异步服务IntentService的讲解与实战(实现四大名著的加载进度条 附源码)
54 0
|
4月前
|
缓存 IDE Java
应用研发平台EMAS中classpath 'com.aliyun.ams:alicloud-android-networkmonitor-plugin:1.3.0-open'这个一直下载不成功,这个需要怎么处理?
应用研发平台EMAS中classpath 'com.aliyun.ams:alicloud-android-networkmonitor-plugin:1.3.0-open'这个一直下载不成功,这个需要怎么处理?
50 1