在我们做开发的时候经常遇到的就是下载了,现在下载的方法有很多很多,那么怎么做到断点续传下载呢!很多人都头疼这个问题,如果我们没有很好的逻辑真不是很容易解决啊。我参考了一下前辈们的资料了整理了一个项目,能实现多个文件的同时下载。
断点续传下载,顾名思义,那就是我们在一次下载未结束时,退出下载,第二次下载时会接着第一次下载的进度继续下载。那么怎么记录第一次下载的数据呢,这里肯定就要用到数据库了。下面就是我创建数据库的一个SQLiteOpenHelper类。用来首次运行时创建数据库。
DBHelper.java
package com.icss.DBHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 建立一个数据库帮助类
*/
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) {
}
}
下面看主界面的布局,在这里,我只设计了一个ListView来显示下载的音乐的名称,和一个开始下载按钮和一个暂停按钮。
布局文件如下:
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" android:weightSum="1">
<ListView android:id="@android:id/list" android:layout_height="wrap_content"
android:layout_width="match_parent" android:layout_weight="0.70"></ListView>
</LinearLayout>
list_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:id="@+id/linearLayout1"
android:layout_width="fill_parent" android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:id="@+id/linearLayout2" android:layout_height="wrap_content"
android:orientation="horizontal" android:layout_marginBottom="5dip">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:id="@+id/tv_resouce_name" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:text="下载