Greendao+多线程断点续传

2024-04-25 06:18

本文主要是介绍Greendao+多线程断点续传,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

客官不要着急,下面给出你的困扰。想要用greendao首先需要配置

1、在app的Gradle中配置:

apply plugin'org.greenrobot.greendao'
dependencies {
        compile 'org.greenrobot:greendao:3.2.0'

}

2、在project的Gradle中配置:

dependencies {         classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'     } }
3.在app的Gradle(android)配置数据库版本等信息

greendao {
schemaVersion 1
daoPackage 'com.bwie.test.greendaodemo.gen'
targetGenDir 'src/main/java'
}
schemaVersion       对应当前数据库版本

daoPackage  GreenDao自动生成代码所在的包名,默认的是在项目包下面新建一个gen

targetGenDir    设置自动生成代码的目录

权限也粘一下的啦

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

因为grenndao的独特性,自动生成三个类,下面只给出实体类以及需要的操作


一点也不吝啬,别着急,实体类在这呢,记得生成实体类之后在buils下make project一下,让他自动生成三大类

@Entitypublic class User {@Idprivate Long id;private Integer thread_id;private Integer start_pos;private Integer end_pos;private Integer compelete_size;private String url;@Generated(hash = 2041931179)public User(Long id, Integer thread_id, Integer start_pos, Integer end_pos,Integer compelete_size, String url) {this.id = id;this.thread_id = thread_id;this.start_pos = start_pos;this.end_pos = end_pos;this.compelete_size = compelete_size;this.url = url;}@Generated(hash = 586692638)public User() {}public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public Integer getThread_id() {return this.thread_id;}public void setThread_id(Integer thread_id) {this.thread_id = thread_id;}public Integer getStart_pos() {return this.start_pos;}public void setStart_pos(Integer start_pos) {this.start_pos = start_pos;}public Integer getEnd_pos() {return this.end_pos;}public void setEnd_pos(Integer end_pos) {this.end_pos = end_pos;}public Integer getCompelete_size() {return this.compelete_size;}public void setCompelete_size(Integer compelete_size) {this.compelete_size = compelete_size;}public String getUrl() {return this.url;}public void setUrl(String url) {this.url = url;}}

好人做到低,下面附上需要的单例模式,因为本人用的是单例模式,用来数据库的初始化,并且获得操作类

public class App extends Application {public static UserDao userDao;@Overridepublic 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();}
}


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

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;}@Overridepublic 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;// 下载器idprivate int startPos;// 开始点private int endPos;// 结束点private int compeleteSize;// 完成度private String url;// 下载文件的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;}@Overridepublic String toString() {return "DownloadInfo [threadId=" + threadId + ", startPos=" + startPos+ ", endPos=" + endPos + ", compeleteSize=" + compeleteSize+ "]";}}

4.这是一个接口类
public class DownloadUtil {private DownloadHttpTool mDownloadHttpTool;private OnDownloadListener onDownloadListener;private int fileSize;private int downloadedSize = 0;@SuppressLint("HandlerLeak")private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.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>() {@Overrideprotected Void doInBackground(Void... arg0) {// TODO Auto-generated method stubmDownloadHttpTool.ready();return null;}@Overrideprotected void onPostExecute(Void result) {// TODO Auto-generated method stubsuper.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.主的activity的类
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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);total= (TextView) findViewById(R.id.textView);start= (Button) findViewById(R.id.start);pause= (Button) findViewById(R.id.delete);mProgressBar= (ProgressBar) findViewById(R.id.progressBar);String urlString = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";String localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/local";mDownloadUtil = new DownloadUtil(2, localPath, "adc.mp4", urlString,this);mDownloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {@Overridepublic void downloadStart(int fileSize) {// TODO Auto-generated method stubLog.w(TAG, "fileSize::" + fileSize);max = fileSize;mProgressBar.setMax(fileSize);}@Overridepublic void downloadProgress(int downloadedSize) {// TODO Auto-generated method stubLog.w(TAG, "Compelete::" + downloadedSize);mProgressBar.setProgress(downloadedSize);total.setText((int) downloadedSize * 100 / max + "%");}@Overridepublic void downloadEnd() {// TODO Auto-generated method stubLog.w(TAG, "ENd");}});start.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubmDownloadUtil.start();}});pause.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubmDownloadUtil.pause();}});}



好了,布局也给你们了

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid: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" /><ProgressBarandroid:id="@+id/progressBar"style="?android:attr/progressBarStyleHorizontal"android:layout_width="fill_parent"android:layout_height="7.5dp"android:layout_below="@+id/textView"android:layout_marginRight="8dp"android:max="100"android:progress="100"android:visibility="visible" /><Buttonandroid:id="@+id/start"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_toEndOf="@+id/textView"android:layout_toRightOf="@+id/textView"android:text="下载" /><Buttonandroid:id="@+id/delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_marginLeft="48dp"android:layout_marginStart="48dp"android:layout_toEndOf="@+id/start"android:layout_toRightOf="@+id/start"android:text="暂停" /></RelativeLayout>

最后,客官们注意了,这里面的下载路径是local,自己更改喽。粘的难免出错,下面是Githb地址

GitHub  

效果图,布局可以更改

这篇关于Greendao+多线程断点续传的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/933890

相关文章

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

多线程解析报表

假如有这样一个需求,当我们需要解析一个Excel里多个sheet的数据时,可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要提示解析完成。 Way1 join import java.time.LocalTime;public class Main {public static void main(String[] args) thro

Java 多线程概述

多线程技术概述   1.线程与进程 进程:内存中运行的应用程序,每个进程都拥有一个独立的内存空间。线程:是进程中的一个执行路径,共享一个内存空间,线程之间可以自由切换、并发执行,一个进程最少有一个线程,线程实际数是在进程基础之上的进一步划分,一个进程启动之后,进程之中的若干执行路径又可以划分成若干个线程 2.线程的调度 分时调度:所有线程轮流使用CPU的使用权,平均分配时间抢占式调度

Java 多线程的基本方式

Java 多线程的基本方式 基础实现两种方式: 通过实现Callable 接口方式(可得到返回值):

JAVA- 多线程

一,多线程的概念 1.并行与并发 并行:多个任务在同一时刻在cpu 上同时执行并发:多个任务在同一时刻在cpu 上交替执行 2.进程与线程 进程:就是操作系统中正在运行的一个应用程序。所以进程也就是“正在进行的程序”。(Windows系统中,我们可以在任务管理器中看 到进程) 线程:是程序运行的基本执行单元。当操作系统执行一个程序时, 会在系统中建立一个进程,该进程必须至少建立一个线

多线程篇(阻塞队列- LinkedBlockingDeque)(持续更新迭代)

目录 一、LinkedBlockingDeque是什么 二、核心属性详解 三、核心方法详解 addFirst(E e) offerFirst(E e) putFirst(E e) removeFirst() pollFirst() takeFirst() 其他 四、总结 一、LinkedBlockingDeque是什么 首先queue是一种数据结构,一个集合中

多线程篇(阻塞队列- LinkedBlockingQueue)(持续更新迭代)

目录 一、基本概要 1. 构造函数 2. 内部成员 二、非阻塞式添加元素:add、offer方法原理 offer的实现 enqueue入队操作 signalNotEmpty唤醒 删除线程(如消费者线程) 为什么要判断if (c == 0)时才去唤醒消费线程呢? 三、阻塞式添加元素:put 方法原理 图解:put线程的阻塞过程 四、非阻塞式移除:poll方法原理 dequ

spring笔记 多线程的支持

spring的工作机制 136  属性编辑器 140 spring事件的体系结构 168 Bean间的关系 109 继承 依赖 引用     Bean的继承          1 为了简化初始化的属性注入;          2 子Bean和父Bean相同的属性值,使用子Bean的     Bean的依赖 Srping控制相互依赖的Bean之间,属性注入的顺序,防止出错  depend-on

【编程底层思考】详解Java的JUC多线程并发编程底层组件AQS的作用及原理

Java中的AbstractQueuedSynchronizer(简称AQS)是位于java.util.concurrent.locks包中的一个核心组件,用于构建锁和其他同步器。AQS为实现依赖于FIFO(先进先出)等待队列的阻塞锁和相关同步器提供了一套高效、可扩展的框架。 一、AQS的作用 统一同步状态管理:AQS提供了一个int类型的成员变量state,用于表示同步状态。子类可以根据自己

多线程的系列文章

Java多线程学习(一)Java多线程入门 Java多线程学习(二)synchronized关键字(1)   Java多线程学习(二)synchronized关键字(2) Java多线程学习(三)volatile关键字 Java多线程学习(四)等待/通知(wait/notify)机制 Java多线程学习(五)线程间通信知识点补充 Java多线程学习(六)Lock锁的使用 Java多