getFileTaskBaseDao() {
45 | return fileTaskBaseDao;
46 | }
47 | public void closeDataBase(){
48 | if (database==null){
49 | database.close();
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/bean/FileItemBean.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.bean;
2 |
3 | import com.xingen.okhttplib.common.utils.FileUtils;
4 |
5 | /**
6 | * Created by ${xinGen} on 2018/1/5.
7 | *
8 | * 每个模块下载信息的实体
9 | */
10 |
11 | public class FileItemBean {
12 | /**
13 | * 起始的角标
14 | */
15 | private long startIndex;
16 | /**
17 | * 上传进度
18 | */
19 | private long progressIndex;
20 | /**
21 | * 唯一标识
22 | */
23 | private String threadName;
24 | /**
25 | * 多表关联的标识
26 | */
27 | private String bindTaskId;
28 | /**
29 | * 当前块的角标
30 | */
31 | private int currentBlock;
32 | /**
33 | * 快数范围值,到什么为止
34 | */
35 | private int blockSize;
36 | /**
37 | * 是否完成
38 | */
39 | private volatile int isFinish=0;
40 | public static final int BLOCK_FINISH=1;
41 | public int getCurrentBlock() {
42 | return currentBlock;
43 | }
44 | public void setCurrentBlock(int currentBlock) {
45 | this.currentBlock = currentBlock;
46 | }
47 | public int getBlockSize() {
48 | return blockSize;
49 | }
50 | public void setBlockSize(int blockSize) {
51 | this.blockSize = blockSize;
52 | }
53 | public String getBindTaskId() {
54 | return bindTaskId;
55 | }
56 | public String getThreadName() {
57 | return threadName;
58 | }
59 | public long getStartIndex() {
60 | return startIndex;
61 | }
62 | public void setStartIndex(long startIndex) {
63 | this.startIndex = startIndex;
64 | }
65 | public int isFinish() {
66 | return isFinish;
67 | }
68 | public void setFinish(int finish) {
69 | isFinish = finish;
70 | }
71 | /**
72 | * 计算出当前模块中上传的进度
73 | * @param total
74 | */
75 | public void handleProgress(int total){
76 | long chunkSize=(currentBlock-1)* FileUtils.CHUNK_LENGTH+total- startIndex;
77 | setProgressIndex(chunkSize);
78 | }
79 | private synchronized void setProgressIndex(long total){
80 | this.progressIndex=total;
81 | }
82 | public synchronized long getProgressIndex() {
83 | return progressIndex;
84 | }
85 | public static class Builder {
86 | private FileItemBean fileItem;
87 | public Builder() {
88 | this.fileItem = new FileItemBean();
89 | }
90 | public Builder setThreadName(String threadName) {
91 | this.fileItem.threadName = threadName;
92 | return this;
93 | }
94 | public Builder setProgressIndex(long total){
95 | this.fileItem.progressIndex=total;
96 | return this;
97 | }
98 | public Builder setCurrentBlock(int currentBlock) {
99 | this.fileItem.currentBlock = currentBlock;
100 | return this;
101 | }
102 | public Builder setBlockSize(int totalBlockSize) {
103 | this.fileItem.blockSize = totalBlockSize;
104 | return this;
105 | }
106 | public Builder setStartIndex(long startIndex) {
107 | fileItem.startIndex = startIndex;
108 | return this;
109 | }
110 | public Builder setFinish(int finish) {
111 | this.fileItem.isFinish = finish;
112 | return this;
113 | }
114 | public Builder setBindTaskId(String bindTaskId) {
115 | this.fileItem.bindTaskId = bindTaskId;
116 | return this;
117 | }
118 | public FileItemBean builder() {
119 | return this.fileItem;
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/bean/FileTaskBean.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.bean;
2 |
3 | /**
4 | * Created by ${xinGen} on 2018/1/6.
5 | */
6 |
7 | public class FileTaskBean {
8 | /**
9 | * 下载地址
10 | */
11 | private String url;
12 | /**
13 | * 文件存储路径
14 | */
15 | private String filePath;
16 | /**
17 | * 下载任务文件的总长度
18 | */
19 | private long fileLength;
20 | /**
21 | *
22 | * 文件的md5值,检验文件的唯一性
23 | *
24 | */
25 | private String md5;
26 | /**
27 | * 是否完成
28 | */
29 | private int state;
30 | /**
31 | * 文件分割的总块数
32 | */
33 | private int totalBlockSize;
34 | /**
35 | * 最后的结果,包含解析的路径等等
36 | */
37 | private String result;
38 |
39 | public String getMd5() {
40 | return md5;
41 | }
42 |
43 | public int getTotalBlockSize() {
44 | return totalBlockSize;
45 | }
46 |
47 | public void setTotalBlockSize(int totalBlockSize) {
48 | this.totalBlockSize = totalBlockSize;
49 | }
50 |
51 | public void setMd5(String md5) {
52 | this.md5 = md5;
53 | }
54 |
55 | public int getState() {
56 | return state;
57 | }
58 | public String getUrl() {
59 | return url;
60 | }
61 | public String getFilePath() {
62 | return filePath;
63 | }
64 | public long getFileLength() {
65 | return fileLength;
66 | }
67 |
68 | public void setFilePath(String filePath) {
69 | this.filePath = filePath;
70 | }
71 | public void setFileLength(long fileLength) {
72 | this.fileLength = fileLength;
73 | }
74 | public void setState(int state) {
75 | this.state = state;
76 | }
77 |
78 | public String getResult() {
79 | return result;
80 | }
81 |
82 | public void setResult(String result) {
83 | this.result = result;
84 | }
85 |
86 | public static class Builder {
87 | private FileTaskBean fileTaskBean;
88 | public Builder(){
89 | this.fileTaskBean =new FileTaskBean();
90 | }
91 | public Builder setState(int state) {
92 | this.fileTaskBean.state = state;
93 | return this;
94 | }
95 | public Builder setMd5(String md5) {
96 | this.fileTaskBean.md5 = md5;
97 | return this;
98 | }
99 | public Builder setDownloadUrl(String downloadUrl) {
100 | this.fileTaskBean.url = downloadUrl;
101 | return this;
102 | }
103 | public Builder setFilePath(String filePath) {
104 | this.fileTaskBean.filePath = filePath;
105 | return this;
106 | }
107 | public Builder setTotalBlockSize(int totalBlockSize) {
108 | this.fileTaskBean.totalBlockSize = totalBlockSize;
109 | return this;
110 | }
111 | public Builder setDownloadTaskLength(long downloadTaskLength) {
112 | this.fileTaskBean.fileLength = downloadTaskLength;
113 | return this;
114 | }
115 | public Builder setResult(String result) {
116 | this.fileTaskBean.result = result;
117 | return this;
118 | }
119 | public FileTaskBean builder(){
120 | return this.fileTaskBean;
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/dao/BaseDao.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.dao;
2 |
3 | import android.database.sqlite.SQLiteOpenHelper;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * Created by ${xinGen} on 2018/1/6.
9 | */
10 |
11 | public interface BaseDao {
12 |
13 | /**
14 | * 获取全部
15 | * @return
16 | */
17 | List queryAll();
18 |
19 | /**
20 | * 指定条件下的查询
21 | * @param select
22 | * @param selectArg
23 | * @return
24 | */
25 | List queryAction(String select, String[] selectArg);
26 |
27 | /**
28 | * 新增
29 | * @param t
30 | * @return
31 | */
32 | long insert(T t);
33 |
34 | /**
35 | * 批量插入
36 | * @param list
37 | * @return
38 | */
39 | int bulkInsert(List list);
40 |
41 | /**
42 | * 更新
43 | * @param t
44 | * @param select
45 | * @param selectArg
46 | * @return
47 | */
48 | int update(T t, String select, String[] selectArg);
49 |
50 | /**
51 | * 指定条件的删除
52 | * @param select
53 | * @param selectArg
54 | * @return
55 | */
56 | int delete(String select, String[] selectArg);
57 |
58 | /**
59 | * 删除全部
60 | */
61 | void deleteAll();
62 |
63 | /**
64 | * 设置数据库
65 | * @param sqLiteOpenHelper
66 | */
67 | void setDataBase(SQLiteOpenHelper sqLiteOpenHelper);
68 | }
69 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/dao/FileItemImp.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.dao;
2 |
3 | import android.content.ContentValues;
4 | import android.database.Cursor;
5 | import android.database.sqlite.SQLiteDatabase;
6 | import android.database.sqlite.SQLiteOpenHelper;
7 |
8 |
9 | import com.xingen.okhttplib.internal.db.bean.FileItemBean;
10 | import com.xingen.okhttplib.internal.db.sqlite.DatabaseConstants;
11 | import com.xingen.okhttplib.internal.db.utils.DBUtils;
12 |
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 | /**
17 | * Created by ${xinGen} on 2018/1/6.
18 | */
19 |
20 | public class FileItemImp implements BaseDao {
21 | private static FileItemImp instance;
22 | private SQLiteOpenHelper sqLiteOpenHelper;
23 | private FileItemImp() {
24 | }
25 | public static synchronized FileItemImp getInstance() {
26 | if (instance == null) {
27 | instance = new FileItemImp();
28 | }
29 | return instance;
30 | }
31 | @Override
32 | public void setDataBase(SQLiteOpenHelper sqLiteOpenHelper) {
33 | this.sqLiteOpenHelper=sqLiteOpenHelper;
34 | }
35 | @Override
36 | public List queryAll() {
37 | return null;
38 | }
39 | private SQLiteDatabase getDataBase(){
40 | return sqLiteOpenHelper.getWritableDatabase();
41 | }
42 | @Override
43 | public List queryAction(String select, String[] selectArg) {
44 | List downloadItemList = new ArrayList<>();
45 | Cursor cursor = null;
46 |
47 | try {
48 | cursor = getDataBase().query(DatabaseConstants.TABLE_NAME_FILE_ITEM, null, select, selectArg, null,null,null,null);
49 | if (cursor != null && cursor.moveToFirst()) {
50 | do {
51 | downloadItemList.add(DBUtils.createDownloadItem(cursor));
52 | } while (cursor.moveToNext());
53 | }
54 | } catch (Exception e) {
55 | e.printStackTrace();
56 | } finally {
57 | if (cursor != null) {
58 | cursor.close();
59 | }
60 | }
61 | return downloadItemList;
62 | }
63 | @Override
64 | public long insert(FileItemBean downloadItem) {
65 | return 0;
66 | }
67 | @Override
68 | public int bulkInsert(List list) {
69 | SQLiteDatabase sqLiteDatabase= getDataBase();
70 | try {
71 | sqLiteDatabase.beginTransaction();
72 | for (int i=0;i{
20 |
21 | private static FileTaskImp instance;
22 |
23 | private FileTaskImp(){}
24 | private SQLiteOpenHelper sqLiteOpenHelper;
25 |
26 | @Override
27 | public void setDataBase(SQLiteOpenHelper sqLiteOpenHelper) {
28 | this.sqLiteOpenHelper=sqLiteOpenHelper;
29 | }
30 | public static synchronized FileTaskImp getInstance(){
31 | if (instance==null){
32 | instance=new FileTaskImp();
33 | }
34 | return instance;
35 | }
36 |
37 | @Override
38 | public List queryAll() {
39 | return null;
40 | }
41 | public SQLiteDatabase getDataBase(){
42 | return sqLiteOpenHelper.getWritableDatabase();
43 | }
44 | @Override
45 | public List queryAction(String select, String[] selectArg) {
46 | List downloadItemList = new ArrayList<>();
47 | Cursor cursor = null;
48 | try {
49 | cursor = getDataBase().query(DatabaseConstants.TABLE_NAME_FILE_TASK, null, select, selectArg, null,null,null);
50 | if (cursor != null && cursor.moveToFirst()) {
51 | do {
52 | downloadItemList.add(DBUtils.createDownloadTask(cursor));
53 | } while (cursor.moveToNext());
54 | }
55 | } catch (Exception e) {
56 | e.printStackTrace();
57 | } finally {
58 | if (cursor != null) {
59 | cursor.close();
60 | }
61 | }
62 | return downloadItemList;
63 | }
64 |
65 | @Override
66 | public long insert(FileTaskBean downloadTaskBean) {
67 |
68 | return getDataBase().insert(DatabaseConstants.TABLE_NAME_FILE_TASK, null,DBUtils.createContentValues(downloadTaskBean));
69 | }
70 |
71 | @Override
72 | public int bulkInsert(List list) {
73 | return 0;
74 | }
75 |
76 | @Override
77 | public int update(FileTaskBean downloadTaskBean, String select, String[] selectArg) {
78 | return this.getDataBase().update(DatabaseConstants.TABLE_NAME_FILE_TASK,DBUtils.createContentValues(downloadTaskBean),select,selectArg);
79 | }
80 | @Override
81 | public int delete(String select, String[] selectArg) {
82 | return this.getDataBase().delete(DatabaseConstants.TABLE_NAME_FILE_TASK,select,selectArg);
83 | }
84 | @Override
85 | public void deleteAll() {
86 |
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/sqlite/DatabaseConstants.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.sqlite;
2 |
3 | import android.provider.BaseColumns;
4 |
5 | /**
6 | * Created by ${xinGen} on 2018/1/5.
7 | */
8 |
9 | public final class DatabaseConstants implements BaseColumns{
10 | /**
11 | * 数据库信息
12 | */
13 | public static final String SQLITE_NAME="fileBlockUpload.db";
14 | public static final int SQLITE_VERSON=1;
15 | /**
16 | * 下载表,及其字段
17 | */
18 | public static final String TABLE_NAME_FILE_TASK ="fileTask";
19 | public static final String COLUMN_URL ="url";
20 | public static final String COLUMN_WRITE_FILE_PATH="filePath";
21 | public static final String COLUMN_STATE="state";
22 | public static final String COLUMN_TASK_LENGTH="taskLength";
23 | public static final String COLUMN_FILE_MD5="md5";
24 | public static final String COLUMN_TOTAL_BLOCK_SIZE="totalBlockSize";
25 | public static final String COLUMN_FILE_RESULT="fileResult";
26 | /**
27 | * 模块下载,及其字段
28 | */
29 | public static final String TABLE_NAME_FILE_ITEM ="fileItem";
30 | public static final String COLUMN_BIND_TASK_ID="taskId";
31 | public static final String COLUMN_THREAD_NAME="threadName";
32 | public static final String COLUMN_START_INDEX="startIndex";
33 | public static final String COLUMN_PROGRESS_INDEX ="progressIndex";
34 | public static final String COLUMN_CURRENT_BLOCK="currentBlockIndex";
35 | public static final String COLUMN_THREAD_BLOCK_SIZE="blockSize";
36 | public static final String COLUMN_BLOCK_FINIS="blockFinish";
37 |
38 | /**
39 | * 创建下载任务的表 的sql语句
40 | */
41 | public static final String CREATE_FILE_TASK = "create table " +
42 | DatabaseConstants.TABLE_NAME_FILE_TASK + "(" +
43 | DatabaseConstants._ID + " integer primary key autoincrement," +
44 | DatabaseConstants.COLUMN_URL + " text," +
45 | DatabaseConstants.COLUMN_WRITE_FILE_PATH + " text," +
46 | DatabaseConstants.COLUMN_TASK_LENGTH + " text," +
47 | DatabaseConstants.COLUMN_FILE_MD5 + " text," +
48 | DatabaseConstants.COLUMN_FILE_RESULT + " text," +
49 | DatabaseConstants.COLUMN_TOTAL_BLOCK_SIZE + " integer," +
50 | DatabaseConstants.COLUMN_STATE + " integer"
51 | + ")";
52 | /**
53 | * 创建多部分下载的表的sql语句
54 | */
55 | public static final String CREATE_FILE_ITEM = "create table " +
56 | DatabaseConstants.TABLE_NAME_FILE_ITEM + "(" +
57 | DatabaseConstants._ID + " integer primary key autoincrement," +
58 | DatabaseConstants.COLUMN_START_INDEX + " integer," +
59 | DatabaseConstants.COLUMN_PROGRESS_INDEX + " integer," +
60 | DatabaseConstants.COLUMN_THREAD_NAME + " text," +
61 | DatabaseConstants.COLUMN_CURRENT_BLOCK+ " integer," +
62 | DatabaseConstants.COLUMN_BLOCK_FINIS + " integer," +
63 | DatabaseConstants.COLUMN_THREAD_BLOCK_SIZE + " integer," +
64 | DatabaseConstants.COLUMN_BIND_TASK_ID + " text"
65 | + ")";
66 | }
67 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/sqlite/UploadFileTaskDatabase.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.sqlite;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.database.sqlite.SQLiteOpenHelper;
6 | import android.util.Log;
7 |
8 | /**
9 | * Created by ${xinGen} on 2018/1/5.
10 | */
11 | public class UploadFileTaskDatabase extends SQLiteOpenHelper {
12 | private static final String TAG=UploadFileTaskDatabase.class.getSimpleName();
13 |
14 | public UploadFileTaskDatabase(Context context) {
15 | super(context, DatabaseConstants.SQLITE_NAME, null, DatabaseConstants.SQLITE_VERSON);
16 | }
17 | @Override
18 | public void onCreate(SQLiteDatabase db) {
19 | Log.i(TAG, "下载任务的数据库执行 onCreate()");
20 | db.execSQL( DatabaseConstants.CREATE_FILE_TASK);
21 | db.execSQL( DatabaseConstants.CREATE_FILE_ITEM);
22 | }
23 | @Override
24 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/db/utils/DBUtils.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.db.utils;
2 |
3 | import android.content.ContentValues;
4 | import android.database.Cursor;
5 |
6 | import com.xingen.okhttplib.internal.db.bean.FileItemBean;
7 | import com.xingen.okhttplib.internal.db.bean.FileTaskBean;
8 | import com.xingen.okhttplib.internal.db.sqlite.DatabaseConstants;
9 |
10 |
11 | /**
12 | * Created by ${xinGen} on 2018/1/16.
13 | */
14 |
15 | public class DBUtils {
16 | public static FileItemBean createDownloadItem(Cursor cursor) {
17 | return new FileItemBean.Builder()
18 | .setStartIndex(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_START_INDEX)))
19 | .setThreadName(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_THREAD_NAME)))
20 | .setProgressIndex(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_PROGRESS_INDEX)))
21 | .setCurrentBlock(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_CURRENT_BLOCK)))
22 | .setFinish(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_BLOCK_FINIS)))
23 | .setBlockSize(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_THREAD_BLOCK_SIZE)))
24 | .setBindTaskId(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_BIND_TASK_ID)))
25 | .builder();
26 | }
27 | public static FileTaskBean createDownloadTask(Cursor cursor) {
28 | return new FileTaskBean.Builder()
29 | .setDownloadTaskLength(Long.valueOf(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_TASK_LENGTH))))
30 | .setDownloadUrl(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_URL)))
31 | .setFilePath(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_WRITE_FILE_PATH)))
32 | .setResult(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_FILE_RESULT)))
33 | .setMd5(cursor.getString(cursor.getColumnIndex(DatabaseConstants.COLUMN_FILE_MD5)))
34 | .setTotalBlockSize(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_TOTAL_BLOCK_SIZE)))
35 | .setState(cursor.getInt(cursor.getColumnIndex(DatabaseConstants.COLUMN_STATE)))
36 | .builder();
37 | }
38 | public static ContentValues createContentValues(FileItemBean downloadItem) {
39 | ContentValues contentValues = new ContentValues();
40 | //url需要转成特殊的字符
41 | contentValues.put(DatabaseConstants.COLUMN_BIND_TASK_ID, downloadItem.getBindTaskId());
42 | contentValues.put(DatabaseConstants.COLUMN_START_INDEX, downloadItem.getStartIndex());
43 | contentValues.put(DatabaseConstants.COLUMN_CURRENT_BLOCK,downloadItem.getCurrentBlock());
44 | contentValues.put(DatabaseConstants.COLUMN_PROGRESS_INDEX,downloadItem.getProgressIndex());
45 | contentValues.put(DatabaseConstants.COLUMN_THREAD_BLOCK_SIZE,downloadItem.getBlockSize());
46 | contentValues.put(DatabaseConstants.COLUMN_THREAD_NAME, downloadItem.getThreadName());
47 | contentValues.put(DatabaseConstants.COLUMN_BLOCK_FINIS, downloadItem.isFinish());
48 | return contentValues;
49 | }
50 | public static ContentValues createContentValues(FileTaskBean downLoadTask) {
51 | ContentValues contentValues = new ContentValues();
52 | contentValues.put(DatabaseConstants.COLUMN_URL, downLoadTask.getUrl());
53 | contentValues.put(DatabaseConstants.COLUMN_WRITE_FILE_PATH, downLoadTask.getFilePath());
54 | contentValues.put(DatabaseConstants.COLUMN_FILE_MD5,downLoadTask.getMd5());
55 | contentValues.put(DatabaseConstants.COLUMN_TASK_LENGTH, String.valueOf(downLoadTask.getFileLength()) );
56 | contentValues.put(DatabaseConstants.COLUMN_STATE,downLoadTask.getState());
57 | contentValues.put(DatabaseConstants.COLUMN_TOTAL_BLOCK_SIZE,downLoadTask.getTotalBlockSize());
58 | contentValues.put(DatabaseConstants.COLUMN_FILE_RESULT,downLoadTask.getResult());
59 | return contentValues;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/dispatch/Dispatcher.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.dispatch;
2 |
3 | /**
4 | * Created by ${xinGen} on 2018/1/19.
5 | */
6 |
7 | public interface Dispatcher {
8 | void dispatch(Runnable runnable);
9 |
10 | void destroy();
11 | }
12 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/dispatch/ThreadDispatcher.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.dispatch;
2 |
3 | import android.os.Handler;
4 | import android.os.HandlerThread;
5 | import android.os.Looper;
6 |
7 | /**
8 | * Created by ${xinGen} on 2018/1/19.
9 | *
10 | * 创建一个后台线程,执行调度任务。
11 | *
12 | */
13 |
14 | public class ThreadDispatcher implements Dispatcher{
15 | private static final String TAG=ThreadDispatcher.class.getName();
16 | private HandlerThread handlerThread;
17 | private final Handler handler;
18 | private Looper looper;
19 | public ThreadDispatcher(){
20 | this.handlerThread=new HandlerThread(TAG);
21 | this.handlerThread.start();
22 | this.looper=this.handlerThread.getLooper();
23 | this.handler=new Handler(this.looper);
24 | }
25 | @Override
26 | public void dispatch(Runnable runnable){
27 | if (handler!=null){
28 | this.handler.post(runnable);
29 | }
30 | }
31 | @Override
32 | public void destroy(){
33 | try {
34 | this.looper.quit();
35 | }catch (Exception e){
36 | e.printStackTrace();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/error/CommonError.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.error;
2 |
3 | /**
4 | * Created by ${xinGen} on 2018/1/29.
5 | */
6 |
7 | public class CommonError extends RuntimeException {
8 | private String msg;
9 | private int code;
10 |
11 | private CommonError() {
12 | }
13 |
14 | public CommonError(int state, String message) {
15 | super(message);
16 | this.msg = message;
17 | this.code = state;
18 | }
19 |
20 | public String getMsg() {
21 | return msg;
22 | }
23 |
24 | public void setMsg(String msg) {
25 | this.msg = msg;
26 | }
27 |
28 | public int getCode() {
29 | return code;
30 | }
31 |
32 | public void setCode(int code) {
33 | this.code = code;
34 | }
35 |
36 | public static class Builder {
37 | private CommonError error;
38 |
39 | public Builder() {
40 | this.error = new CommonError();
41 | }
42 |
43 | public Builder setMsg(String msg) {
44 | this.error.msg = msg;
45 | return this;
46 | }
47 |
48 | public Builder setCode(int code) {
49 | this.error.code = code;
50 | return this;
51 | }
52 |
53 | public CommonError builder() {
54 | return error;
55 | }
56 | }
57 |
58 | public static final class State {
59 | /**
60 | * 空指针
61 | */
62 | public static final int error_null = 1;
63 | /**
64 | * 网络异常
65 | */
66 | public static final int error_net = 2;
67 | /**
68 | * 解析异常
69 | */
70 | public static final int error_parser = 3;
71 | /**
72 | * 类型转换异常
73 | */
74 | public static final int error_class = 4;
75 | /**
76 | * IO异常
77 | */
78 | public static final int error_io=5;
79 | /**
80 | * 未知异常
81 | */
82 | public static final int error_unknown=5;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/execute/NetExecutor.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.execute;
2 |
3 |
4 |
5 | import com.xingen.okhttplib.internal.request.BaseRequest;
6 |
7 | import okhttp3.OkHttpClient;
8 |
9 | /**
10 | * Created by ${xinGen} on 2018/1/11.
11 | *
12 | * 一个网络执行的接口
13 | */
14 |
15 | public interface NetExecutor {
16 | void setOkHttpClient(OkHttpClient okHttpClient);
17 | void executeRequest(BaseRequest baseRequest);
18 | }
19 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/execute/NetExecutorImp.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.execute;
2 |
3 | import android.util.Log;
4 |
5 | import com.google.gson.JsonSyntaxException;
6 | import com.xingen.okhttplib.common.utils.LogUtils;
7 | import com.xingen.okhttplib.internal.error.CommonError;
8 | import com.xingen.okhttplib.internal.executor.MainExecutor;
9 | import com.xingen.okhttplib.internal.okhttp.OkHttpProvider;
10 | import com.xingen.okhttplib.internal.request.BaseRequest;
11 | import com.xingen.okhttplib.internal.response.ResponseResult;
12 |
13 | import java.io.IOException;
14 | import java.net.ConnectException;
15 | import java.net.SocketException;
16 | import java.net.SocketTimeoutException;
17 | import java.net.UnknownHostException;
18 |
19 | import okhttp3.Call;
20 | import okhttp3.OkHttpClient;
21 | import okhttp3.Request;
22 | import okhttp3.Response;
23 |
24 | /**
25 | * Created by ${xinGen} on 2018/1/19.
26 | */
27 |
28 | public class NetExecutorImp implements NetExecutor {
29 | private final String TAG = NetExecutorImp.class.getSimpleName();
30 | private OkHttpClient okHttpClient;
31 | private MainExecutor mainExecutor;
32 |
33 | public NetExecutorImp(MainExecutor mainExecutor) {
34 | this.mainExecutor = mainExecutor;
35 | }
36 |
37 | @Override
38 | public void setOkHttpClient(OkHttpClient okHttpClient) {
39 | this.okHttpClient = okHttpClient;
40 | }
41 |
42 | @Override
43 | public void executeRequest(final BaseRequest baseRequest) {
44 | Log.i(TAG, Thread.currentThread().getName() + " 执行网络方法 executeRequest()");
45 | try {
46 | if (isCancel(baseRequest)) {
47 | return;
48 | }
49 | Request request = baseRequest.createOkHttpRequest();
50 | LogUtils.i(TAG, "okhttp开始创建request ");
51 | Call call = OkHttpProvider.createCall(okHttpClient, request);
52 | baseRequest.setCall(call);
53 | if (isCancel(baseRequest)) {
54 | return;
55 | }
56 | LogUtils.i(TAG, "okhttp开始执行request ");
57 | final Response response = OkHttpProvider.executeSynchronous(call);
58 | if (isCancel(baseRequest) || response == null) {
59 | closeResource(response);
60 | return;
61 | }
62 | LogUtils.i(TAG, "okhttp 获取 response " + response);
63 | if (response.isSuccessful()) {
64 | LogUtils.i(TAG, "okhttp请求成功,开始解析 ");
65 | ResponseResult responseResult ;
66 | try {
67 | responseResult = baseRequest.parseResponse(response);
68 | }catch (JsonSyntaxException e){
69 | responseResult=new ResponseResult(new CommonError(CommonError.State.error_parser,e.getMessage()));
70 | }catch ( IOException e){
71 | responseResult=new ResponseResult(new CommonError(CommonError.State.error_io,e.getMessage()));
72 | }catch (NullPointerException e){
73 | responseResult=new ResponseResult(new CommonError(CommonError.State.error_null,e.getMessage()));
74 | }catch (CommonError e){
75 | responseResult=new ResponseResult(e);
76 | }catch (Exception e){
77 | responseResult=new ResponseResult(new CommonError(CommonError.State.error_unknown,e.getMessage()));
78 | }
79 | this.deliverResponse(baseRequest,responseResult);
80 | } else {
81 | deliverError(new CommonError(CommonError.State.error_net,"请求失败"),baseRequest);
82 | }
83 | closeResource(response);
84 | } catch (final Exception e) {
85 | deliverError(e, baseRequest);
86 | }
87 | }
88 |
89 | private void deliverError(Exception e, final BaseRequest baseRequest) {
90 | final CommonError commonError;
91 | if (e instanceof ConnectException || e instanceof SocketTimeoutException || e instanceof UnknownHostException || e instanceof SocketException) {
92 | commonError = new CommonError(CommonError.State.error_net, e.getMessage());
93 | } else if (e instanceof IOException) {
94 | commonError = new CommonError(CommonError.State.error_io, e.getMessage());
95 | } else {
96 | commonError = new CommonError(CommonError.State.error_unknown, e.getMessage());
97 | }
98 | LogUtils.i(TAG, "okhttp请求过程中发生异常 " + e.getMessage());
99 | this.deliverResult(new Runnable() {
100 | @Override
101 | public void run() {
102 | baseRequest.deliverError(commonError);
103 | }
104 | });
105 | }
106 | private void deliverResponse(final BaseRequest request, final ResponseResult responseResult){
107 | this.deliverResult(new Runnable() {
108 | @Override
109 | public void run() {
110 | if (request.isCancel()){
111 | return;
112 | }
113 | if (responseResult.error!=null){
114 | request.deliverError(responseResult.error);
115 | }else {
116 | request.deliverResult(responseResult.t);
117 | }
118 | }
119 | });
120 | }
121 |
122 | private void deliverResult(Runnable runnable) {
123 | this.mainExecutor.execute(runnable);
124 | }
125 |
126 | private boolean isCancel(BaseRequest baseRequest) {
127 | if (baseRequest.isCancel()) {
128 | baseRequest.releaseResource();
129 | Log.i(TAG, TAG + " 执行过程,请求被取消");
130 | return true;
131 | }
132 | return false;
133 | }
134 |
135 | /**
136 | * 关闭response
137 | *
138 | * @param response
139 | */
140 | private void closeResource(Response response) {
141 | if (response != null) {
142 | response.body().close();
143 | }
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/executor/MainExecutor.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.executor;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.support.annotation.NonNull;
6 |
7 | import java.util.concurrent.Executor;
8 |
9 | /**
10 | * Created by ${xinGen} on 2018/1/19.
11 | * 主线程执行工具
12 | */
13 |
14 | public class MainExecutor implements Executor {
15 | private final Handler mainHandler;
16 | public MainExecutor() {
17 | mainHandler =new Handler(Looper.getMainLooper());
18 | }
19 | @Override
20 | public void execute(@NonNull Runnable command) {
21 | mainHandler.post(command);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/json/parser/OkHttpBaseParser.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.json.parser;
2 |
3 | import java.io.IOException;
4 |
5 | import okhttp3.Response;
6 |
7 | /**
8 | * Created by ${xinGen} on 2018/1/22.
9 | */
10 |
11 | public interface OkHttpBaseParser {
12 | T parser(Response response) throws IOException;
13 | }
14 |
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/json/parser/OkHttpJsonParser.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.json.parser;
2 |
3 | import com.google.gson.Gson;
4 | import com.xingen.okhttplib.internal.json.utils.GsonUtils;
5 |
6 | import java.lang.reflect.Type;
7 |
8 | import okhttp3.Response;
9 |
10 | /**
11 | * Created by ${xinGen} on 2018/1/22.
12 | *
13 | * 参考:gson包下的 TypeToken来仿写
14 | *
15 | * 这里需要抽象类
16 | */
17 |
18 | public abstract class OkHttpJsonParser implements OkHttpBaseParser {
19 | public Type type;
20 | private Gson gson;
21 | public OkHttpJsonParser() {
22 | this.type=GsonUtils.getSuperclassTypeParameter(getClass());
23 | this.gson=new Gson();
24 | }
25 | @Override
26 | public T parser(Response response) {
27 | try {
28 | String s = response.body().string();
29 | return parser(s);
30 | }catch (Exception e){
31 | e.printStackTrace();
32 | }
33 | return null;
34 | }
35 | public T parser(String s){
36 | try {
37 |
38 |
39 | T t = GsonUtils.toBean(gson, s, type);
40 | return t;
41 | }catch (Exception e){
42 | e.printStackTrace();
43 | }
44 | return null;
45 | }
46 | }
--------------------------------------------------------------------------------
/OkHttpLibSDK/src/main/java/com/xingen/okhttplib/internal/json/utils/GsonUtils.java:
--------------------------------------------------------------------------------
1 | package com.xingen.okhttplib.internal.json.utils;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.internal.$Gson$Types;
5 | import com.google.gson.reflect.TypeToken;
6 |
7 | import java.lang.reflect.ParameterizedType;
8 | import java.lang.reflect.Type;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | /**
13 | * Created by ${xinGen} on 2018/1/10.
14 | *
15 | * Gson解析泛型类型数据的关键就是TypeToken
16 | *
17 | */
18 |
19 | public class GsonUtils {
20 | public static T toBean(String content, Class mclass) {
21 | return toBean(new Gson(), content, mclass);
22 | }
23 |
24 | /**
25 | * 解析最基本对象
26 | * @param gson
27 | * @param content
28 | * @param mclass
29 | * @param
30 | * @return
31 | */
32 | public static T toBean(Gson gson, String content, Class mclass) {
33 | T t = null;
34 | try {
35 | t = gson.fromJson(content, mclass);
36 | } catch (Exception e) {
37 | e.printStackTrace();
38 | t = null;
39 | }
40 | return t;
41 | }
42 |
43 | /**
44 | * 解析实体类嵌套泛型,List嵌套泛型等等。
45 | * @param gson
46 | * @param content
47 | * @param type
48 | * @param
49 | * @return
50 | */
51 | public static T toBean(Gson gson,String content,Type type){
52 | try {
53 | T t=gson.fromJson(content,type);
54 | return t;
55 | }catch (Exception e){
56 | e.printStackTrace();
57 | }
58 | return null;
59 | }
60 | /**
61 | * 根据返回值来,制定泛型类型
62 | * 解析实体类嵌套泛型,List嵌套泛型等等。
63 | * @param gson
64 | * @param content
65 | * @param
66 | * @return
67 | */
68 | public static T toBean(Gson gson,String content){
69 | try {
70 | T t=gson.fromJson(content,new TypeToken(){}.getType());
71 | return t;
72 | }catch (Exception e){
73 | e.printStackTrace();
74 | }
75 | return null;
76 | }
77 |
78 | /**
79 | *
80 | * @param gson
81 | * @param content
82 | * @param
83 | * @return
84 | */
85 | public static List toBeanList(Gson gson, String content) {
86 | try {
87 | Type type = new TypeToken>() {}.getType();
88 | List list = gson.fromJson(content, type);
89 | return list;
90 | } catch (Exception e) {
91 | e.printStackTrace();
92 | }
93 | return null;
94 | }
95 |
96 | /**
97 | *
98 | * @param gson
99 | * @param content
100 | * @param
101 | * @return
102 | */
103 | public static Map toBeanMap(Gson gson, String content) {
104 | try {
105 | Type type = new TypeToken