初学者----Android Greendao+多线程断点续传

关于GreenDao

greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。
关于greenDAO的概念可以看官网greenDAO

greenDAO 优势

1、一个精简的库
2、性能最大化
3、内存开销最小化
4、易于使用的 APIs
5、对 Android 进行高度优化

GreenDao 3.0使用

GreenDao 3.0采用注解的方式来定义实体类,通过gradle插件生成相应的代码。

一.在(Project的)build.gradle内:

dependencies {
       ....
        //greendao
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
       
    }
二. 在(Module:app)build.gradle内:
//greendao
apply plugin: 'org.greenrobot.greendao'

android {
   ........
}
//自定义路径
greendao {
    schemaVersion 1
    daoPackage '自己MainActivity所在的包名.gen'
    targetGenDir 'src/main/java'
}

dependencies {
    .....
    //greendao
    compile 'org.greenrobot:greendao:3.2.0'
}
在gradle的根模块中加入上述代码,就完成了我们的基本配置了。
属性介绍:
schemaVersion--> 指定数据库schema版本号,迁移等操作会用到;
daoPackage --> dao的包名, GreenDao自动生成代码所在的包名,默认的是在项目包下面新建一个gen.

targetGenDir-->生成数据库文件的目录。

三.创建一个User的实体类

@Entity
public class User {
    @Id
    private Long id;
    private Integer thread_id;
    private Integer start_pos;
    private Integer end_pos;
    private Integer compelete_size;
    private String url;
}
四,MakeProject,自动生成三个类

编译项目,User实体类会自动编译,生成get、set方法并且会在com.anye.greendao.gen目录下生成三个文件;


五.数据库的初始化(单例模式)

public class MyApp extends Application {
    public static UserDao userDao;

    @Override
    public void onCreate() {
        super.onCreate();
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "lenvess.db", null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        DaoSession daoSession = daoMaster.newSession();
        userDao = daoSession.getUserDao();
    }
}
不要忘了在 AndroidManifest.xml注册MyApp

到此处GreenDao的前期工作完成..........

多线程下载移步http://blog.csdn.net/inter_native/article/details/78603256

实现的效果是:


具体的类:

1.主要是记录的类,修改,添加和最后下载完清空数据库的类

public class DownlaodSqlTool {
    /**
     * 创建下载的具体信息
     */
    public void insertInfos(List<DownloadInfo> infos) {
        for (DownloadInfo info : infos) {
            User user = new User(null, info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl());
            userDao.insert(user);
        }
    }

    /**
     * 得到下载具体信息
     */
    public List<DownloadInfo> getInfos(String urlstr) {
        List<DownloadInfo> list = new ArrayList<DownloadInfo>();
        List<User> list1 = userDao.queryBuilder().where(UserDao.Properties.Url.eq(urlstr)).build().list();
        for (User user : list1) {
            DownloadInfo infoss = new DownloadInfo(
                    user.getThread_id(), user.getStart_pos(), user.getEnd_pos(),
                    user.getCompelete_size(), user.getUrl());
            Log.d("main-----", infoss.toString());
            list.add(infoss);
        }

        return list;
    }

    /**
     * 更新数据库中的下载信息
     */
    public void updataInfos(int threadId, int compeleteSize, String urlstr) {
        User user = userDao.queryBuilder()
                .where(UserDao.Properties.Thread_id.eq(threadId), UserDao.Properties.Url.eq(urlstr)).build().unique();
        user.setCompelete_size(compeleteSize);
        userDao.update(user);
    }

    /**
     * 下载完成后删除数据库中的数据
     */
    public void delete(String url) {
        userDao.deleteAll();
    }

}
2. 多线程下载的实践类
public class DownloadHttpTool {
    /**
     * 利用Http协议进行多线程下载具体实践类
     */

    private static final String TAG = DownloadHttpTool.class.getSimpleName();
    private int threadCount;//线程数量
    private String urlstr;//URL地址
    private Context mContext;
    private Handler mHandler;
    private List<DownloadInfo> downloadInfos;//保存下载信息的类

    private String localPath;//目录
    private String fileName;//文件名
    private int fileSize;
    private DownlaodSqlTool sqlTool;//文件信息保存的数据库操作类

    private enum Download_State {
        Downloading, Pause, Ready;//利用枚举表示下载的三种状态
    }

    private Download_State state = Download_State.Ready;//当前下载状态

    private int globalCompelete = 0;//所有线程下载的总数

    public DownloadHttpTool(int threadCount, String urlString,
                            String localPath, String fileName, Context context, Handler handler) {
        super();
        this.threadCount = threadCount;
        this.urlstr = urlString;
        this.localPath = localPath;
        this.mContext = context;
        this.mHandler = handler;
        this.fileName = fileName;
        sqlTool = new DownlaodSqlTool();
    }

    //在开始下载之前需要调用ready方法进行配置
    public void ready() {
        Log.w(TAG, "ready");
        globalCompelete = 0;
        downloadInfos = sqlTool.getInfos(urlstr);
        if (downloadInfos.size() == 0) {
            initFirst();
        } else {
            File file = new File(localPath + "/" + fileName);
            if (!file.exists()) {
                sqlTool.delete(urlstr);
                initFirst();
            } else {
                fileSize = downloadInfos.get(downloadInfos.size() - 1)
                        .getEndPos();
                for (DownloadInfo info : downloadInfos) {
                    globalCompelete += info.getCompeleteSize();
                }
                Log.w(TAG, "globalCompelete:::" + globalCompelete);
            }
        }
    }

    public void start() {
        Log.w(TAG, "start");
        if (downloadInfos != null) {
            if (state == Download_State.Downloading) {
                return;
            }
            state = Download_State.Downloading;
            for (DownloadInfo info : downloadInfos) {
                Log.v(TAG, "startThread");
                new DownloadThread(info.getThreadId(), info.getStartPos(),
                        info.getEndPos(), info.getCompeleteSize(),
                        info.getUrl()).start();
            }
        }
    }

    public void pause() {
        state = Download_State.Pause;
    }

    public void delete() {
        compelete();
        File file = new File(localPath + "/" + fileName);
        file.delete();
    }

    public void compelete() {
        sqlTool.delete(urlstr);
    }

    public int getFileSize() {
        return fileSize;
    }

    public int getCompeleteSize() {
        return globalCompelete;
    }

    //第一次下载初始化
    private void initFirst() {
        Log.w(TAG, "initFirst");
        try {
            URL url = new URL(urlstr);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            fileSize = connection.getContentLength();
            Log.w(TAG, "fileSize::" + fileSize);
            File fileParent = new File(localPath);
            if (!fileParent.exists()) {
                fileParent.mkdir();
            }
            File file = new File(fileParent, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            // 本地访问文件
            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
            accessFile.setLength(fileSize);
            accessFile.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int range = fileSize / threadCount;
        downloadInfos = new ArrayList<DownloadInfo>();
        for (int i = 0; i < threadCount - 1; i++) {
            DownloadInfo info = new DownloadInfo(i, i * range, (i + 1) * range
                    - 1, 0, urlstr);
            downloadInfos.add(info);
        }
        DownloadInfo info = new DownloadInfo(threadCount - 1, (threadCount - 1)
                * range, fileSize - 1, 0, urlstr);
        downloadInfos.add(info);
        sqlTool.insertInfos(downloadInfos);
    }

    //自定义下载线程
    private class DownloadThread extends Thread {

        private int threadId;
        private int startPos;
        private int endPos;
        private int compeleteSize;
        private String urlstr;
        private int totalThreadSize;

        public DownloadThread(int threadId, int startPos, int endPos,
                              int compeleteSize, String urlstr) {
            this.threadId = threadId;
            this.startPos = startPos;
            this.endPos = endPos;
            totalThreadSize = endPos - startPos + 1;
            this.urlstr = urlstr;
            this.compeleteSize = compeleteSize;
        }

        @Override
        public void run() {
            HttpURLConnection connection = null;
            RandomAccessFile randomAccessFile = null;
            InputStream is = null;
            try {
                randomAccessFile = new RandomAccessFile(localPath + "/"
                        + fileName, "rwd");
                randomAccessFile.seek(startPos + compeleteSize);
                URL url = new URL(urlstr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Range", "bytes="
                        + (startPos + compeleteSize) + "-" + endPos);
                is = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int length = -1;
                while ((length = is.read(buffer)) != -1) {
                    randomAccessFile.write(buffer, 0, length);
                    compeleteSize += length;
                    Message message = Message.obtain();
                    message.what = threadId;
                    message.obj = urlstr;
                    message.arg1 = length;
                    mHandler.sendMessage(message);
                    sqlTool.updataInfos(threadId, compeleteSize, urlstr);
                    Log.w(TAG, "Threadid::" + threadId + "    compelete::"
                            + compeleteSize + "    total::" + totalThreadSize);
                    if (compeleteSize >= totalThreadSize) {
                        break;
                    }
                    if (state != Download_State.Downloading) {
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    randomAccessFile.close();
                    connection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
3. 保存每个下载线程下载信息的类
public class DownloadInfo {
    /**
     * 保存每个下载线程下载信息类
     *
     */

    private int threadId;// 下载器id
    private int startPos;// 开始点
    private int endPos;// 结束点
    private int compeleteSize;// 完成度
    private String url;// 下载文件的URL地址

    省略构造方法,get,set...
}
4. 接口类

public class DownloadUtil {
    private DownloadHttpTool mDownloadHttpTool;
    private OnDownloadListener onDownloadListener;

    private int fileSize;
    private int downloadedSize = 0;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int length = msg.arg1;
            synchronized (this) {//加锁保证已下载的正确性
                downloadedSize += length;
            }
            if (onDownloadListener != null) {
                onDownloadListener.downloadProgress(downloadedSize);
            }
            if (downloadedSize >= fileSize) {
                mDownloadHttpTool.compelete();
                if (onDownloadListener != null) {
                    onDownloadListener.downloadEnd();
                }
            }
        }

    };

    public DownloadUtil(int threadCount, String filePath, String filename,
                        String urlString, Context context) {

        mDownloadHttpTool = new DownloadHttpTool(threadCount, urlString,
                filePath, filename, context, mHandler);
    }

    //下载之前首先异步线程调用ready方法获得文件大小信息,之后调用开始方法
    public void start() {
        new AsyncTask<Void,Void,Void>() {

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                mDownloadHttpTool.ready();
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                fileSize = mDownloadHttpTool.getFileSize();
                downloadedSize = mDownloadHttpTool.getCompeleteSize();
                Log.w("Tag", "downloadedSize::" + downloadedSize);
                if (onDownloadListener != null) {
                    onDownloadListener.downloadStart(fileSize);
                }
                mDownloadHttpTool.start();
            }
        }.execute();
    }

    public void pause() {
        mDownloadHttpTool.pause();
    }

    public void delete(){
        mDownloadHttpTool.delete();
    }

    public void reset(){
        mDownloadHttpTool.delete();
        start();
    }

    public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
        this.onDownloadListener = onDownloadListener;
    }

    //下载回调接口
    public interface OnDownloadListener {
        public void downloadStart(int fileSize);

        public void downloadProgress(int downloadedSize);//记录当前所有线程下总和

        public void downloadEnd();
    }
}
5.MainActivity类:
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ProgressBar mProgressBar;
    private Button start;
    private Button pause;


    private TextView total;
    private int max;
    private DownloadUtil mDownloadUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }
    //初始化控件
    private void initView() {
        total= (TextView) findViewById(R.id.textView);
        start= (Button) findViewById(R.id.start);
        pause= (Button) findViewById(R.id.delete);
        mProgressBar= (ProgressBar) findViewById(R.id.progressBar);

    }
    //获取数据
    private void initData() {
        //url
        String urlString = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";
        //存储路径
        String localPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/localVideo";
        //实例化DownloadUtil,传入线程数,保存地址,文件名,网络文件地址,上下文
        mDownloadUtil = new DownloadUtil(2, localPath, "adc.mp4", urlString,
                this);

        mDownloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
            @Override
            public void downloadStart(int fileSize) {
                Log.w(TAG, "fileSize::" + fileSize);
                max = fileSize;
                mProgressBar.setMax(fileSize);
            }

            @Override
            public void downloadProgress(int downloadedSize) {
                Log.w(TAG, "Compelete::" + downloadedSize);
                mProgressBar.setProgress(downloadedSize);
                total.setText((int) downloadedSize * 100 / max + "%");
            }

            @Override
            public void downloadEnd() {
                Log.w(TAG, "ENd");
            }
        });
        //开始下载
        start.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mDownloadUtil.start();
            }
        });
        //暂停
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mDownloadUtil.pause();
            }
        });
    }
}
最后是activity_main.xml布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:orientation="vertical"
    tools:context="xxx.com.drowloadthreadgdijkplayerdemo.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="23dp"
        android:layout_marginStart="23dp"
        android:layout_marginTop="18dp"
        android:text="TextView" />

    <ProgressBar
        android:layout_marginTop="20dp"
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="10dp"
        android:layout_below="@+id/textView"
        android:layout_marginRight="8dp"
        android:max="100"
        android:progress="0"
        android:visibility="visible" />

    <Button
        android:layout_marginTop="50dp"
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toEndOf="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:text="下载" />


    <Button
        android:layout_marginTop="50dp"
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="暂停" />

</LinearLayout>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值