閱讀624 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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 = "https://192.168.1.5/android/test.zip";
    private String downloadFile1 = "https://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)
            {
                e.printStackTrace();
            } 
           
        }
    }
   
}

最後更新:2017-04-02 06:51:48

  上一篇:go 如何利用Handler更新android的UI
  下一篇:go Android 視圖切換效果