天天看點

android多任務同時下載下傳

學習android快兩個月了,一直堅持從迷茫中尋找可以得到的盡可能多的東西

想做一個下載下傳功能,當然理想的功能要支援多任務同時下載下傳,斷點續傳的功能,我想一步一步來,首先困難擺在了多任務這裡

開始我的思路是在一個service中啟動下載下傳的流操作,然後通過service中聲明一個activity中的handler更新ui(比如進度條。。。)

可是我發現在service中聲明一個activity中的handler是做不到的(可能隻是我做不到吧,無法申請記憶體)

于是,我決定在activity中直接啟動線程,讓其運作,調用自身的handler來更新ui,沒想到在這個下載下傳activity onpause()的時候,線程還是活的,也就是說可以繼續下載下傳,下例是我做的一個兩個任務同時下載下傳的小例子,後面會把理想中的功能都陸續添加上的。。。

package onerain.multhreaddownload;

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 onerain.multhreaddownload.downloadservicer.downloadthread;

import android.app.activity;

import android.content.intent;

import android.os.bundle;

import android.os.environment;

import android.os.handler;

import android.os.looper;

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://192.168.1.5/android/test.zip";

    private string downloadfile1 = "http://192.168.1.5/android/test1.exe";

    //聲明已經讀過的長度變量

    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)

            } 

}

繼續閱讀