美文网首页Android
android 多线程断点续传下载 一

android 多线程断点续传下载 一

作者: 吕中宜 | 来源:发表于2015-11-13 17:59 被阅读795次

文章出处
  想做一个下载功能,当然理想的功能要支持多任务同时下载,断点续传的功能,我想一步一步来,首先困难摆在了多任务这里
  开始我的思路是在一个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: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" />  
    <ProgressBar style="?android:attr/progressBarStyleHorizontal"  
        android:layout_height="wrap_content" android:id="@+id/progressBar2"  
        android:layout_width="fill_parent"></ProgressBar>  
  
    <TextView android:layout_width="fill_parent" android:id="@+id/textView2"  
        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>  

activity程序:

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) {  
                e.printStackTrace();  
            }  
  
        }  
    }  
  
}  

程序运行效果:

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

相关文章

  • Android下载文件(一)下载进度&断点续传

    索引 Android下载文件(一)下载进度&断点续传 Android下载文件(二)多线程并发&断点续传(待续) A...

  • Android多线程下载

    Android 多线程下载,断点续传 https://github.com/liu8021203/Download...

  • 多线程断点

    Android多线程断点续传下载 原理 其实断点续传的原理很简单,从字面上理解,所谓断点续传就是从停止的地方重新下...

  • 多线程下载及其断点续传

    Android 多线程下载及其断点续传原理,BitMap高效加载大图,图片三级缓存原理(Lru算法原理) 一、多线...

  • 实现Android多线程断点续传下载

    断点续传原理一、从上次的位置继续下载。 二、从上次写入的文件继续写入。 多线程结合断点续传下载 多线程无非是将待下...

  • Okhttp多线程断点续传

    目录 1、断点续传相关定义2、多线程下载实现方案 1、断点续传相关定义 1.1、断点续传: 记录上次下载的位置,下...

  • Android原生下载(上篇)基本逻辑+断点续传

    零、前言 1.今天带来的是Android原生下载的上篇,主要核心是断点续传,多线程下载将会在下篇介绍2.本例使用了...

  • 造轮子 - RxDownload

    基于RxJava打造的下载工具, 支持多线程下载和断点续传, 智能判断是否支持断点续传等功能 标签(空格分隔): ...

  • FileDownloader的简单使用

    FileDownlaoder 支持多任务下载 支持多线程下载 支持 断点续传 github地址:https://g...

  • android 中断点续传

    android 中断点续传 单线程断点续传 所谓的断点续传就是在下载一个文件时,文件没有完全下载,中途暂停,那么再...

网友评论

    本文标题:android 多线程断点续传下载 一

    本文链接:https://www.haomeiwen.com/subject/olfkhttx.html