天天看点

android 多线程断点续传下载 一

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

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

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

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

main.xml配置:

[html] view

plaincopy

<?xml version="1.0" encoding="utf-8"?>  

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:orientation="vertical" android:layout_width="fill_parent"  

    android:layout_height="fill_parent">  

    <progressbar style="?android:attr/progressbarstylehorizontal"  

        android:layout_height="wrap_content" android:id="@+id/progressbar1"  

        android:layout_width="fill_parent"></progressbar>  

    <textview android:layout_width="fill_parent" android:id="@+id/textview1"  

        android:layout_height="wrap_content" />  

        android:layout_height="wrap_content" android:id="@+id/progressbar2"  

    <textview android:layout_width="fill_parent" android:id="@+id/textview2"  

</linearlayout>  

androidmanifest.xml配置:

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

activity程序:

[java] view

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 string root = environment.getexternalstoragedirectory()  

            .getabsolutepath() + file.separator;  

    private string downloadfile = "http://gongxue.cn/yingyinkuaiche/uploadfiles_9323/201008/2010082909434077.mp3";  

    private string downloadfile1 = "http://gongxue.cn/yingyinkuaiche/uploadfiles_9323/201008/2010082909434077.mp3";  

    // 声明已经读过的长度变量  

    private int hasread = 0;  

    public void oncreate(bundle savedinstancestate) {  

        super.oncreate(savedinstancestate);  

        setcontentview(r.layout.main);  

        pb1 = (progressbar) findviewbyid(r.id.progressbar1);  

        tv1 = (textview) findviewbyid(r.id.textview1);  

        pb2 = (progressbar) findviewbyid(r.id.progressbar2);  

        tv2 = (textview) findviewbyid(r.id.textview2);  

        download(downloadfile, root, pb1, tv1);  

        download(downloadfile1, root, pb2, 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 progressbar progressbar;  

        private 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 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;  

            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) {  

                    // todo auto-generated catch block  

                    e.printstacktrace();  

                }  

            }  

            try {  

                url fileurl = new url(this.url);  

                httpurlconnection conn = (httpurlconnection) fileurl  

                        .openconnection();  

                // 获取文件大小  

                size = conn.getcontentlength();  

                inputstream is = conn.getinputstream();  

                outputstream os = new fileoutputstream(targetfilename);  

                while ((len = is.read(buffer)) != -1) {  

                    os.write(buffer);  

                    hasdownload += len;  

                    rate = (hasdownload * 100 / size);  

                    msg = new message();  

                    msg.arg1 = rate;  

                    myhandler.sendmessage(msg);  

                    system.out.println(rate + "%");  

            } catch (malformedurlexception e) {  

                // todo auto-generated catch block  

                e.printstacktrace();  

            } catch (ioexception e) {  

}  

程序运行效果:

android 多线程断点续传下载 一

源码下载

下一步将实现断点续传和暂停删除开始事件,更多更新敬请关注....  

继续阅读