Android 多线程断点下载demo实现

先来一张效果图:

Android 多线程断点下载demo实现_第1张图片

主要实现思路:

每一个下载都是通过RandomAccessFile对下载资源的总长进行切割之后,根据我们设置的线程多少进行计算之后开启多线程下载的。而每一个任务都是一个AsyncTask。数据的存储都是通过SQL来进行,保证整个下载任务的断续不受影响。

一:数据库操作的工具类,根据数据库设计而生成的bean类:

public class DBHelper  extends SQLiteOpenHelper{
    //download.db-->数据库名
    public DBHelper(Context context) {
        super(context, "download.db", null, 1);
    }

    /**
     * 在download.db数据库下创建一个download_info表存储下载信息
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "
                + "start_pos integer, end_pos integer, compelete_size integer,url char)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

数据库操作类,包括查看,保存,更新,获取,以及下载完毕之后的删除操作。

public class Dao {
    private static Dao dao=null;
    private Context context;
    private  Dao(Context context) {
        this.context=context;
    }
    public static  Dao getInstance(Context context){
        if(dao==null){
            dao=new Dao(context);
        }
        return dao;
    }
    public  SQLiteDatabase getConnection() {
        SQLiteDatabase sqliteDatabase = null;
        try {
            sqliteDatabase= new DBHelper(context).getReadableDatabase();
        } catch (Exception e) {
        }
        return sqliteDatabase;
    }

    /**
     * 查看数据库中是否有数据
     */
    public synchronized boolean isHasInfors(String urlstr) {
        SQLiteDatabase database = getConnection();
        int count = -1;
        Cursor cursor = null;
        try {
            String sql = "select count(*)  from download_info where url=?";
            cursor = database.rawQuery(sql, new String[] { urlstr });
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != database) {
                database.close();
            }
            if (null != cursor) {
                cursor.close();
            }
        }
        return count == 0;
    }

    /**
     * 保存 下载的具体信息
     */
    public synchronized void saveInfos(List infos) {
        SQLiteDatabase database = getConnection();
        try {
            for (DownloadInfo info : infos) {
                String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";
                Object[] bindArgs = { info.getThreadId(), info.getStartPos(),
                        info.getEndPos(), info.getCompeleteSize(),
                        info.getUrl() };
                database.execSQL(sql, bindArgs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != database) {
                database.close();
            }
        }
    }

    /**
     * 得到下载具体信息
     */
    public synchronized List getInfos(String urlstr) {
        List list = new ArrayList<>();
        SQLiteDatabase database = getConnection();
        Cursor cursor = null;
        try {
            String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";
            cursor = database.rawQuery(sql, new String[] { urlstr });
            while (cursor.moveToNext()) {
                DownloadInfo info = new DownloadInfo(cursor.getInt(0),
                        cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
                        cursor.getString(4));
                list.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != database) {
                database.close();
            }
            if (null != cursor) {
                cursor.close();
            }
        }
        return list;
    }

    /**
     * 更新数据库中的下载信息
     */
    public synchronized void updataInfos(int threadId, int compeleteSize, String urlstr) {
        SQLiteDatabase database = getConnection();
        try {
            String sql = "update download_info set compelete_size=? where thread_id=? and url=?";
            Object[] bindArgs = { compeleteSize, threadId, urlstr };
            database.execSQL(sql, bindArgs);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != database) {
                database.close();
            }
        }
    }

    /**
     * 下载完成后删除数据库中的数据
     */
    public synchronized void delete(String url) {
        SQLiteDatabase database = getConnection();
        try {
            database.delete("download_info", "url=?", new String[] { url });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != database) {
                database.close();
            }
        }
    }

}

根据数据库设计的字段自己编写的bean类:

public class DownloadInfo {
    private int threadId;//下载器id
    private int startPos;//开始点
    private int endPos;//结束点
    private int compeleteSize;//完成度
    private String url;//下载器网络标识
    public DownloadInfo(int threadId, int startPos, int endPos,
                        int compeleteSize,String url) {
        this.threadId = threadId;
        this.startPos = startPos;
        this.endPos = endPos;
        this.compeleteSize = compeleteSize;
        this.url=url;
    }
    public DownloadInfo() {
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public int getThreadId() {
        return threadId;
    }
    public void setThreadId(int threadId) {
        this.threadId = threadId;
    }
    public int getStartPos() {
        return startPos;
    }
    public void setStartPos(int startPos) {
        this.startPos = startPos;
    }
    public int getEndPos() {
        return endPos;
    }
    public void setEndPos(int endPos) {
        this.endPos = endPos;
    }
    public int getCompeleteSize() {
        return compeleteSize;
    }
    public void setCompeleteSize(int compeleteSize) {
        this.compeleteSize = compeleteSize;
    }

    @Override
    public String toString() {
        return "DownloadInfo [threadId=" + threadId
                + ", startPos=" + startPos + ", endPos=" + endPos
                + ", compeleteSize=" + compeleteSize +"]";
    }

}

从DownLoadInfo中获取到的几个数据要返回给activity进行进度的更新的实体类

public class LoadInfo {

    public int fileSize;//文件大小
    private int complete;//完成度
    private String urlstring;//下载器标识
    public LoadInfo(int fileSize, int complete, String urlstring) {
        this.fileSize = fileSize;
        this.complete = complete;
        this.urlstring = urlstring;
    }
    public LoadInfo() {
    }
    public int getFileSize() {
        return fileSize;
    }
    public void setFileSize(int fileSize) {
        this.fileSize = fileSize;
    }
    public int getComplete() {
        return complete;
    }
    public void setComplete(int complete) {
        this.complete = complete;
    }
    public String getUrlstring() {
        return urlstring;
    }
    public void setUrlstring(String urlstring) {
        this.urlstring = urlstring;
    }
    @Override
    public String toString() {
        return "LoadInfo [fileSize=" + fileSize + ", complete=" + complete
                + ", urlstring=" + urlstring + "]";
    }


}

二:编写关键的DownLoader类,所有下载逻辑在这里进行,并连接数据库工具类进行操作。

首先就是构造,我们需要获取到的数据,肯定要包括自己设计的数据库里边的字段的数据,其次肯定还要知道多线程的指定数,

最后就是需要一个在activity中定义好的handler来进行进度的传递。

 public DownLoader(String urlstr, String localfile, int threadcount,
                      Context context, Handler mHandler) {
        this.urlstr = urlstr;
        this.localfile = localfile;
        this.threadcount = threadcount;
        this.mHandler = mHandler;
        this.context = context;
    }

那么下载的状态也是必须要提前准备好的

 private static final int INIT = 1;//定义三种下载的状态:初始化状态,正在下载状态,暂停状态
    private static final int DOWNLOADING = 2;
    private static final int PAUSE = 3;
 /**
     *判断是否正在下载
     */
    public boolean isdownloading() {
        return state == DOWNLOADING;
    }
 //删除数据库中urlstr对应的下载器信息
    public void delete(String urlstr) {
        Dao.getInstance(context).delete(urlstr);
    }
    //设置暂停
    public void pause() {
        state = PAUSE;
    }
    //重置下载状态
    public void reset() {
        state = INIT;
    }

开始进入整个下载的逻辑

首先是判断是否是第一次下载:

 /**
     * 判断是否是第一次 下载
     */
    private boolean isFirst(String urlstr) {
        return Dao.getInstance(context).isHasInfors(urlstr);
    }

如果是第一次下载,就要知道整个下载资源的总长度:

/**
     * 初始化
     */
    private void init() {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            fileSize = connection.getContentLength();

            File file = new File(localfile);
            if (!file.exists()) {
                file.createNewFile();
            }
            // 本地访问文件
            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
            accessFile.setLength(fileSize);
            accessFile.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

总长度获取到之后,我们就需要通过线程的数量来进行计算每条线程开始的断点的位置,并且将每条线程的任务用bean类进行保存,并存储在list中,然后进行数据库的save。

            int range = fileSize / threadcount;
            infos = new ArrayList<>();
            for (int i = 0; i < threadcount - 1; i++) {
                DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);
                infos.add(info);
            }
            DownloadInfo info = new DownloadInfo(threadcount - 1,(threadcount - 1) * range, fileSize - 1, 0, urlstr);
            infos.add(info);
            //保存infos中的数据到数据库
            Dao.getInstance(context).saveInfos(infos);

那么如果不是第一次下载该资源,就需要先从数据库中获取到下载的信息。因为是断点下载,仅需要通过for循环计算出已下载的资源的总长度

            //得到数据库中已有的urlstr的下载器的具体信息
            infos = Dao.getInstance(context).getInfos(urlstr);
            Log.v("TAG", "not isFirst size=" + infos.size());
            int size = 0;//下载资源的总量
            int compeleteSize = 0;//已经下载完成的资源总量
            for (DownloadInfo info : infos) {
                compeleteSize += info.getCompeleteSize();
                size += info.getEndPos() - info.getStartPos() + 1;
            }
而因为我们要在activity中更新progressBar的进度条,所以我们需要将completeSize、filesize给传递到activity中刷新ui,而为了区分开每个prgressBar对应的下载任务,我们就需要一个key来进行区分,每个资源的url肯定是不同的,也是最适合这个工作的,所以就可以得到以下的代码:
 /**
     * 得到downloader里的信息
     * 首先进行判断是否是第一次下载,如果是第一次就要进行初始化,并将下载器的信息保存到数据库中
     * 如果不是第一次下载,那就要从数据库中读出之前下载的信息(起始位置,结束为止,文件大小等),并将下载信息返回给下载器
     */
    public LoadInfo getDownloaderInfors() {
        if (isFirst(urlstr)) {
            Log.v("TAG", "isFirst");
            init();
            int range = fileSize / threadcount;
            infos = new ArrayList<>();
            for (int i = 0; i < threadcount - 1; i++) {
                DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);//因为是第一次,所以completeSize为0;
                infos.add(info);
            }
            DownloadInfo info = new DownloadInfo(threadcount - 1,(threadcount - 1) * range, fileSize - 1, 0, urlstr);
            infos.add(info);
            //保存infos中的数据到数据库
            Dao.getInstance(context).saveInfos(infos);
            //创建一个LoadInfo对象记载下载器的具体信息
            LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
            return loadInfo;
        } else {
            //得到数据库中已有的urlstr的下载器的具体信息
            infos = Dao.getInstance(context).getInfos(urlstr);
            Log.v("TAG", "not isFirst size=" + infos.size());
            int size = 0;
            int compeleteSize = 0;
            for (DownloadInfo info : infos) {
                compeleteSize += info.getCompeleteSize();//因为已经下载过,所以需要计算出已下载的completeSize进行界面更新。
                size += info.getEndPos() - info.getStartPos() + 1;
            }
            return new LoadInfo(size, compeleteSize, urlstr);
        }
    }

在每次下载任务之前需要先去获取一下getDownloaderInfors()下载的信息,注意这个信息因为包含数据库操作,且init中需要联网获取资源总长,所以需要在子线程中进行。

接下来开始进行具体的下载工作:

/**
     * 利用线程开始下载数据
     */
    public void download() {
        if (infos != null) {
            if (state == DOWNLOADING)
                return;
            state = DOWNLOADING;
            for (DownloadInfo info : infos) {
                new MyThread(info.getThreadId(), info.getStartPos(),
                        info.getEndPos(), info.getCompeleteSize(),
                        info.getUrl()).start();
            }
        }
    }

断点下载就需要将我们前面准备工作中获取到的DownLoadInfo的集合进行遍历,将每一个线程应该从哪儿到哪儿的下载任务区分好,整个线程的逻辑如下:

 public class MyThread extends Thread {
        private int threadId;
        private int startPos;
        private int endPos;
        private int compeleteSize;
        private String urlstr;

        public MyThread(int threadId, int startPos, int endPos,
                        int compeleteSize, String urlstr) {
            this.threadId = threadId;
            this.startPos = startPos;
            this.endPos = endPos;
            this.compeleteSize = compeleteSize;
            this.urlstr = urlstr;
        }
        @Override
        public void run() {
            HttpURLConnection connection = null;
            RandomAccessFile randomAccessFile = null;
            InputStream is = null;
            try {
                URL url = new URL(urlstr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                // 设置范围,格式为Range:bytes x-y;
                connection.setRequestProperty("Range", "bytes="+(startPos + compeleteSize) + "-" + endPos);

                randomAccessFile = new RandomAccessFile(localfile, "rwd");
                randomAccessFile.seek(startPos + compeleteSize);
                // 将要下载的文件写到保存在保存路径下的文件中
                is = connection.getInputStream();
                byte[] buffer = new byte[4096];
                int length = -1;
                while ((length = is.read(buffer)) != -1) {
                    randomAccessFile.write(buffer, 0, length);
                    compeleteSize += length;
                    // 更新数据库中的下载信息
                    Dao.getInstance(context).updataInfos(threadId, compeleteSize, urlstr);
                    // 用消息将下载信息传给进度条,对进度条进行更新
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = urlstr;
                    message.arg1 = length;
                    mHandler.sendMessage(message);
                    if (state == PAUSE) {
                        return;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (connection!=null)connection.disconnect();
                    if (randomAccessFile!=null)randomAccessFile.close();
                    if (is!=null)is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

计算每个线程起始的下载位置,通过randomAccessFile.seek(startPos + compeleteSize)来快进到开始位置。然后进行while循环下载,不断的更新数据库(这一块的数据库操作很频繁,还在想怎么优化,但是感觉怎么优化都不太合适),并通过handler将完成度传递给activity进行界面更新。并且判断当前状态是否是已暂停,已暂停就直接跳出循环停止任务。最后记得关闭流。

这样整个下载工具类就结束了,接下来就是activity中对该类的调用以及界面的更新了、

三:Activity中的代码逻辑

首先是准备工作:

     // 固定下载的资源路径,这里可以设置网络上的地址
    private static final String URL = "http://download.haozip.com/";
    // 固定存放下载的音乐的路径:SD卡目录下
    private static final String SD_PATH = "/mnt/sdcard/";
    // 存放各个下载器
    private Map downloaders = new HashMap();
    // 存放与下载器对应的进度条
    private Map ProgressBars = new HashMap();

这里将downloader和progressbar存储在map中,并且将下载的url作为key,这样就保证了数据的唯一。

数据的展示是使用的listview和adapter进行操作:

显示数据的准备:

// 显示listView,这里可以随便添加
    private void showListView() {
        List> data = new ArrayList>();
        Map map = new HashMap();
        map.put("name", "haozip_v3.1.exe");
        data.add(map);
        map = new HashMap();
        map.put("name", "haozip_v3.1_hj.exe");
        data.add(map);
        map = new HashMap();
        map.put("name", "haozip_v2.8_x64_tiny.exe");
        data.add(map);
        map = new HashMap();
        map.put("name", "haozip_v2.8_tiny.exe");
        data.add(map);
        DownLoadAdapter adapter=new DownLoadAdapter(this,data);
        setListAdapter(adapter);
    }

adapter中也就是显示一下资源名,这里就不粘贴了。

item中的布局文件:



    
        
        

直接给每个item的button设置onclick事件,在activity中进行操作。(progressBar是在代码中new出来的,更方便控制)。

/**
     * 响应开始下载按钮的点击事件
     */
    public void startDownload(View v) {
        // 得到textView的内容
        LinearLayout layout = (LinearLayout) v.getParent();
        String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
        String urlstr = URL + resouceName;
        String localfile = SD_PATH + resouceName;
        //设置下载线程数为4,这里是我为了方便随便固定的
        String threadcount = "4";
        DownloadTask downloadTask=new DownloadTask(v);
        downloadTask.execute(urlstr,localfile,threadcount);

    };

点击开始按钮之后,开启一个AsyncTask来进行下载的逻辑。

 class DownloadTask extends AsyncTask {
        DownLoader downloader=null;
        View v=null;
        String urlstr=null;
        public DownloadTask(final View v){
            this.v=v;
        }
        @Override
        protected void onPreExecute() {
            Button btn_start=(Button)((View)v.getParent()).findViewById(R.id.btn_start);
            Button btn_pause=(Button)((View)v.getParent()).findViewById(R.id.btn_pause);
            btn_start.setVisibility(View.GONE);
            btn_pause.setVisibility(View.VISIBLE);
        }
        @Override
        protected LoadInfo doInBackground(String... params) {
            urlstr=params[0];
            String localfile=params[1];
            int threadcount=Integer.parseInt(params[2]);
            // 初始化一个downloader下载器
            downloader = downloaders.get(urlstr);
            if (downloader == null) {
                downloader = new DownLoader(urlstr, localfile, threadcount, MainActivity.this, mHandler);
                downloaders.put(urlstr, downloader);
            }
            if (downloader.isdownloading())
                return null;
            // 得到下载信息类的个数组成集合
            return downloader.getDownloaderInfors();
        }
        @Override
        protected void onPostExecute(LoadInfo loadInfo) {
            if(loadInfo!=null){
                // 显示进度条
                showProgress(loadInfo, urlstr, v);
                // 调用方法开始下载
                downloader.download();
            }
        }

    };

DownloadTask需要将button这个view通过构造方法传递过来,在准备阶段进行切换,将开始按钮隐藏,暂停按钮开启(当然也可以两个按钮都同时存在,就不用这么麻烦)。

在doInBackground中先进行DownLoader的初始化并且put到map中。这一步在downloader中主要是获取到资源总长以及分段生成DownloadInfo实体类,和保存这些实体类的list集合。最后获取到loadInfo,在下面进行界面的更新。

在onPostExecute()中先是进行界面的更新(毕竟有可能是下载过数据的),然后开始进行分段下载。

 /**
     * 显示进度条
     */
    private void showProgress(LoadInfo loadInfo, String url, View v) {
        ProgressBar bar = ProgressBars.get(url);
        if (bar == null) {//new出一个progressBar并进行addView添加到item中
            bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
            bar.setMax(loadInfo.getFileSize());//根据在上一步骤中获取到的资源总长度设置bar的最大值
            bar.setProgress(loadInfo.getComplete());
            ProgressBars.put(url, bar);//put到map中
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 5);
            ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
        }
    }

最后就是更新ui了,在activity中new一个handler,在Downloader初始化时传递过去,在下载中不断发送进度,在activity中获取到并及时更新:

 /**
     * 利用消息处理机制适时更新进度条
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String url = (String) msg.obj;
                int length = msg.arg1;
                ProgressBar bar = ProgressBars.get(url);
                if (bar != null) {
                    // 增加指定的进度
                    bar.incrementProgressBy(length);
                    if (bar.getProgress() == bar.getMax()) {
                        LinearLayout layout = (LinearLayout) bar.getParent();
                        TextView resouceName=(TextView)layout.findViewById(R.id.tv_resouce_name);
                        Toast.makeText(MainActivity.this, "["+resouceName.getText()+"]下载完成!", Toast.LENGTH_SHORT).show();
                        // 下载完成后清除进度条并将map中的数据清空
                        layout.removeView(bar);
                        ProgressBars.remove(url);
                        downloaders.get(url).delete(url);
                        downloaders.get(url).reset();
                        downloaders.remove(url);
                        Button btn_start=(Button)layout.findViewById(R.id.btn_start);
                        Button btn_pause=(Button)layout.findViewById(R.id.btn_pause);
                        btn_pause.setVisibility(View.GONE);
                        btn_start.setVisibility(View.GONE);
                    }
                }
            }
        }
    };

这里首先要注意,因为是多线程下载,且传递的message中是每一个线程下载的length,不是总长度,所以这边需要调用

bar.incrementProgressBy(length);

方法进行progressBar的更新,不能直接采用setProgress(length)的方法。

最后就是下载完毕之后记得UI得操作,提示用户,以及数据的删除。

附上activity的整体代码以及adapter的代码:

public class DownLoadAdapter extends BaseAdapter{
    private LayoutInflater mInflater;
    private List> data;
    private Context context;
    private OnClickListener click;

    public DownLoadAdapter(Context context,List> data) {
        this.context=context;
        mInflater = LayoutInflater.from(context);
        this.data=data;
    }
    public void refresh(List> data) {
        this.data=data;
        this.notifyDataSetChanged();
    }
    public void setOnclick(OnClickListener click) {
        this.click=click;
    }


    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Map bean=data.get(position);
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item, null);
            holder = new ViewHolder();
            holder.resouceName=(TextView) convertView.findViewById(R.id.tv_resouce_name);
            holder.startDownload=(Button) convertView.findViewById(R.id.btn_start);
            holder.pauseDownload=(Button) convertView.findViewById(R.id.btn_pause);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.resouceName.setText(bean.get("name"));
        return convertView;
    }
    public OnClickListener getClick() {
        return click;
    }
    public void setClick(OnClickListener click) {
        this.click = click;
    }
    private class ViewHolder {
        public TextView resouceName;
        public Button startDownload;
        public Button pauseDownload;
    }
}
public class MainActivity extends AppCompatActivity {

    private String[] urls={"http://jzvd.nathen.cn/c494b340ff704015bb6682ffde3cd302/64929c369124497593205a4190d7d128-5287d2089db37e62345123a1be272f8b.mp4",
    "http://jzvd.nathen.cn/63f3f73712544394be981d9e4f56b612/69c5767bb9e54156b5b60a1b6edeb3b5-5287d2089db37e62345123a1be272f8b.mp4",
    "http://jzvd.nathen.cn/b201be3093814908bf987320361c5a73/2f6d913ea25941ffa78cc53a59025383-5287d2089db37e62345123a1be272f8b.mp4",
     "http://jzvd.nathen.cn/d2438fd1c37c4618a704513ad38d68c5/68626a9d53ca421c896ac8010f172b68-5287d2089db37e62345123a1be272f8b.mp4",
    "http://jzvd.nathen.cn/25a8d119cfa94b49a7a4117257d8ebd7/f733e65a22394abeab963908f3c336db-5287d2089db37e62345123a1be272f8b.mp4",
    "http://jzvd.nathen.cn/7512edd1ad834d40bb5b978402274b1a/9691c7f2d7b74b5e811965350a0e5772-5287d2089db37e62345123a1be272f8b.mp4",
    "http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4"

};

    // 固定存放下载的音乐的路径:SD卡目录下
    private static final String SD_PATH = "/mnt/sdcard/";
    // 存放各个下载器
    private Map downloaders = new HashMap();
    // 存放与下载器对应的进度条
    private Map ProgressBars = new HashMap();
    /**
     * 利用消息处理机制适时更新进度条
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String url = (String) msg.obj;
                int length = msg.arg1;
                ProgressBar bar = ProgressBars.get(url);
                if (bar != null) {
                    // 设置进度条按读取的length长度更新
                    bar.incrementProgressBy(length);
                    if (bar.getProgress() == bar.getMax()) {
                        LinearLayout layout = (LinearLayout) bar.getParent();
                        TextView resouceName=(TextView)layout.findViewById(R.id.tv_resouce_name);
                        Toast.makeText(MainActivity.this, "["+resouceName.getText()+"]下载完成!", Toast.LENGTH_SHORT).show();
                        // 下载完成后清除进度条并将map中的数据清空
                        layout.removeView(bar);
                        ProgressBars.remove(url);
                        downloaders.get(url).delete(url);
                        downloaders.get(url).reset();
                        downloaders.remove(url);
                        Button btn_start=(Button)layout.findViewById(R.id.btn_start);
                        Button btn_pause=(Button)layout.findViewById(R.id.btn_pause);
                        btn_pause.setVisibility(View.GONE);
                        btn_start.setVisibility(View.GONE);
                    }
                }
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showListView();
    }
    // 显示listView,这里可以随便添加
    private void showListView() {
        List> data = new ArrayList>();
        for (int i=0;i map = new HashMap();
            map.put("name", urls[i]);
            data.add(map);
        }
        DownLoadAdapter adapter=new DownLoadAdapter(this,data);
        setListAdapter(adapter);
    }

    private void setListAdapter(DownLoadAdapter adapter) {
        ListView listView=findViewById(R.id.list);
        listView.setAdapter(adapter);
    }

    /**
     * 响应开始下载按钮的点击事件
     */
    public void startDownload(View v) {
        // 得到textView的内容
        LinearLayout layout = (LinearLayout) v.getParent();
        String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
        String urlstr = resouceName;
        String localfile = SD_PATH + resouceName.substring(resouceName.lastIndexOf("/"));
        //设置下载线程数为4,这里是我为了方便随便固定的
        String threadcount = "4";
        DownloadTask downloadTask=new DownloadTask(v);
        downloadTask.execute(urlstr,localfile,threadcount);

    };
    class DownloadTask extends AsyncTask {
        DownLoader downloader=null;
        View v=null;
        String urlstr=null;
        public DownloadTask(final View v){
            this.v=v;
        }
        @Override
        protected void onPreExecute() {
            Button btn_start=(Button)((View)v.getParent()).findViewById(R.id.btn_start);
            Button btn_pause=(Button)((View)v.getParent()).findViewById(R.id.btn_pause);
            btn_start.setVisibility(View.GONE);
            btn_pause.setVisibility(View.VISIBLE);
        }
        @Override
        protected LoadInfo doInBackground(String... params) {
            urlstr=params[0];
            String localfile=params[1];
            int threadcount=Integer.parseInt(params[2]);
            // 初始化一个downloader下载器
            downloader = downloaders.get(urlstr);
            if (downloader == null) {
                downloader = new DownLoader(urlstr, localfile, threadcount, MainActivity.this, mHandler);
                downloaders.put(urlstr, downloader);
            }
            if (downloader.isdownloading())
                return null;
            // 得到下载信息类的个数组成集合
            return downloader.getDownloaderInfors();
        }
        @Override
        protected void onPostExecute(LoadInfo loadInfo) {
            if(loadInfo!=null){
                // 显示进度条
                showProgress(loadInfo, urlstr, v);
                // 调用方法开始下载
                downloader.download();
            }
        }

    };
    /**
     * 显示进度条
     */
    private void showProgress(LoadInfo loadInfo, String url, View v) {
        ProgressBar bar = ProgressBars.get(url);
        if (bar == null) {
            bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
            bar.setMax(loadInfo.getFileSize());
            bar.setProgress(loadInfo.getComplete());
            ProgressBars.put(url, bar);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 5);
            ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
        }
    }
    /**
     * 响应暂停下载按钮的点击事件
     */
    public void pauseDownload(View v) {
        LinearLayout layout = (LinearLayout) v.getParent();
        String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
        String urlstr =resouceName;
        downloaders.get(urlstr).pause();
        Button btn_start=(Button)((View)v.getParent()).findViewById(R.id.btn_start);
        Button btn_pause=(Button)((View)v.getParent()).findViewById(R.id.btn_pause);
        btn_pause.setVisibility(View.GONE);
        btn_start.setVisibility(View.VISIBLE);
    }
}
本项目已上传github: 点击打开链接




你可能感兴趣的:(Android)