pull/2/head
lyy 8 years ago
parent af40d3049d
commit 57f804cc89
  1. 10
      downloadutil/src/main/java/com/arialyy/downloadutil/DownloadManager.java
  2. 9
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadCommand.java
  3. 41
      downloadutil/src/main/java/com/arialyy/downloadutil/core/Task.java
  4. 32
      downloadutil/src/main/java/com/arialyy/downloadutil/core/inf/IPool.java
  5. 27
      downloadutil/src/main/java/com/arialyy/downloadutil/core/pool/CachePool.java
  6. 14
      downloadutil/src/main/java/com/arialyy/downloadutil/entity/DownloadEntity.java
  7. 195
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/DbEntity.java
  8. 330
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/DbUtil.java
  9. 16
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/Id.java
  10. 16
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/Ignore.java
  11. 38
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/SqlHelper.java
  12. 326
      downloadutil/src/main/java/com/arialyy/downloadutil/util/SQLHelper.java
  13. 34
      downloadutil/src/main/java/com/arialyy/downloadutil/util/Util.java

@ -47,6 +47,16 @@ public class DownloadManager {
*/
public static final String ACTION_FAIL = "ACTION_FAIL";
/**
* 下载实体
*/
public static final String DATA = "DOWNLOAD_ENTITY";
/**
* 位置
*/
public static final String CURRENT_LOCATION = "CURRENT_LOCATION";
private Context mContext;
private DownloadManager(Context context) {

@ -0,0 +1,9 @@
package com.arialyy.downloadutil.core;
/**
* Created by lyy on 2016/8/14.
* 命令抽象类
*/
public abstract class DownloadCommand {
}

@ -2,6 +2,7 @@ package com.arialyy.downloadutil.core;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.util.Log;
@ -9,7 +10,6 @@ import com.arialyy.downloadutil.DownloadManager;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.inf.IDownloadListener;
import com.arialyy.downloadutil.util.DownLoadUtil;
import com.arialyy.downloadutil.util.SQLHelper;
import java.net.HttpURLConnection;
@ -24,7 +24,6 @@ public class Task {
Handler outHandler;
Context context;
DownLoadUtil util;
SQLHelper sqlHelper;
private Task() {
util = new DownLoadUtil();
@ -60,13 +59,6 @@ public class Task {
util.cancelDownload();
}
/**
* 存储下载实体
*/
private void saveDownloadEntity(DownloadEntity entity) {
}
/**
* 下载监听类
*/
@ -89,20 +81,24 @@ public class Task {
@Override
public void onPreDownload(HttpURLConnection connection) {
super.onPreDownload(connection);
long len = connection.getContentLength();
Intent preIntent = new Intent();
preIntent.addCategory(context.getPackageName());
long len = connection.getContentLength();
downloadEntity.setFileSize(len);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendIntent(DownloadManager.ACTION_PRE, -1);
}
@Override
public void onResume(long resumeLocation) {
super.onResume(resumeLocation);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendIntent(DownloadManager.ACTION_RESUME, resumeLocation);
}
@Override
public void onStart(long startLocation) {
super.onStart(startLocation);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendIntent(DownloadManager.ACTION_START, startLocation);
}
@Override
@ -117,21 +113,42 @@ public class Task {
@Override
public void onStop(long stopLocation) {
super.onStop(stopLocation);
downloadEntity.setState(DownloadEntity.STATE_STOP);
sendIntent(DownloadManager.ACTION_STOP, stopLocation);
}
@Override
public void onCancel() {
super.onCancel();
downloadEntity.setState(DownloadEntity.STATE_CANCEL);
sendIntent(DownloadManager.ACTION_CANCEL, -1);
downloadEntity.deleteData();
}
@Override
public void onComplete() {
super.onComplete();
downloadEntity.setState(DownloadEntity.STATE_COMPLETE);
downloadEntity.setDownloadComplete(true);
sendIntent(DownloadManager.ACTION_COMPLETE, -1);
}
@Override
public void onFail() {
super.onFail();
downloadEntity.setState(DownloadEntity.STATE_FAIL);
sendIntent(DownloadManager.ACTION_FAIL, -1);
}
private void sendIntent(String action, long location) {
downloadEntity.save();
Intent intent = new Intent();
intent.addCategory(context.getPackageName());
intent.putExtra(action, downloadEntity);
if (location != -1) {
intent.putExtra(DownloadManager.CURRENT_LOCATION, location);
}
context.sendBroadcast(intent);
}
}

@ -0,0 +1,32 @@
package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/14.
* 任务池
*/
public interface IPool {
/**
* 将下载任务添加到任务池中
*
* @param task
*/
public void putTask(Task task);
/**
* 通过下载链接获取下载任务
*
* @param downloadUrl 下载链接
* @return 下载任务
*/
public Task getTask(String downloadUrl);
/**
* 删除任务池中的下载任务
*
* @param task 下载任务
* @return true:移除成功
*/
public boolean removeTask(Task task);
}

@ -0,0 +1,27 @@
package com.arialyy.downloadutil.core.pool;
import com.arialyy.downloadutil.core.Task;
import com.arialyy.downloadutil.core.inf.IPool;
/**
* Created by lyy on 2016/8/14.
* 任务缓存池所有下载任务最先缓存在这个池中
*/
public class CachePool implements IPool {
@Override
public synchronized void putTask(Task task) {
}
@Override
public synchronized Task getTask(String downloadUrl) {
return null;
}
@Override
public synchronized boolean removeTask(Task task) {
return false;
}
}

@ -3,15 +3,17 @@ package com.arialyy.downloadutil.entity;
import android.os.Parcel;
import android.os.Parcelable;
import com.arialyy.downloadutil.orm.DbEntity;
/**
* Created by lyy on 2015/12/25.
* 下载实体
*/
public class DownloadEntity implements Parcelable, Cloneable {
public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
/**
* 其它状态
*/
public static final int STATE_OTHER = 7;
public static final int STATE_OTHER = -1;
/**
* 失败状态
*/
@ -29,13 +31,13 @@ public class DownloadEntity implements Parcelable, Cloneable {
*/
public static final int STATE_WAIT = 3;
/**
* 未完成状态
* 下载中
*/
public static final int STATE_UN_COMPLETE = 4;
public static final int STATE_DOWNLOAD_ING = 4;
/**
* 下载
* 取消下载
*/
public static final int STATE_DOWNLOAD_ING = 5;
public static final int STATE_CANCEL = 5;
private String downloadUrl; //下载路径
private String downloadPath; //保存路径

@ -0,0 +1,195 @@
package com.arialyy.downloadutil.orm;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import com.arialyy.downloadutil.util.Util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by lyy on 2015/11/2.
* 所有数据库实体父类
*/
public class DbEntity {
private static final String TAG = "DbEntity";
private volatile static SQLiteDatabase mDb = null;
private volatile static DbUtil mUtil;
private Context mContext;
private static final Object LOCK = new Object();
protected int rowID = -1;
protected DbEntity() {
}
public DbEntity(Context context) {
this(context, true);
}
public DbEntity(Context context, boolean newTable) {
mContext = context;
init(newTable);
}
private void init(boolean newTable) {
if (mDb == null) {
synchronized (LOCK) {
if (mDb == null) {
SqlHelper mHelper = new SqlHelper(mContext);
mDb = mHelper.getWritableDatabase();
mUtil = DbUtil.getInstance(mDb);
}
}
}
if (newTable && !mUtil.tableExists(this)) {
mUtil.createTable(this);
}
}
/**
* 获取所有行的rowid
*/
public int[] getRowId() {
Cursor cursor = mUtil.getRowId(this);
int[] ids = new int[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
ids[i] = cursor.getInt(cursor.getColumnIndex("rowid"));
i++;
}
return ids;
}
/**
* 获取rowid
*/
public int getRowId(@NonNull Object[] wheres, @NonNull Object[] values) {
return mUtil.getRowId(this, wheres, values);
}
/**
* 删除当前数据
*/
public void deleteData() {
mUtil.delData(this, new Object[]{"rowid"}, new Object[]{rowID});
}
/**
* 根据条件删除数据
*/
public void deleteData(@NonNull Object[] wheres, @NonNull Object[] values) {
mUtil.delData(this, wheres, values);
}
/**
* 修改数据
*/
public void update() {
mUtil.modifyData(this);
}
/**
* 插入数据
*/
public void save() {
mUtil.insertData(this);
}
/**
* 查询所有数据
*
* @return 没有数据返回null
*/
public <T extends DbEntity> List<T> findAllData(Class<T> clazz) {
Cursor cursor = mUtil.findAllData(this);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
}
/**
* 查询一组数据
*
* @return 没有数据返回null
*/
public <T extends DbEntity> List<T> findDatas(Class<T> clazz, @NonNull Object[] wheres, @NonNull Object[] values) {
Cursor cursor = mUtil.findData(this, wheres, values);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
}
/**
* 查询一行数据
*
* @return 没有数据返回null
*/
public <T extends DbEntity> T findData(Class<T> clazz, @NonNull Object[] wheres, @NonNull Object[] values) {
Cursor cursor = mUtil.findData(this, wheres, values);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor).get(0) : null;
}
/**
* 根据数据游标创建一个具体的对象
*/
private <T extends DbEntity> List<T> newInstanceEntity(Class<T> clazz, Cursor cursor) {
Field[] fields = Util.getFields(clazz);
List<T> entitys = new ArrayList<>();
if (fields != null && fields.length > 0) {
try {
while (cursor.moveToNext()) {
Class[] paramTypes = {Context.class, boolean.class};
Object[] params = {mContext, false};
Constructor<T> con = clazz.getConstructor(paramTypes);
T entity = con.newInstance(params);
for (Field field : fields) {
field.setAccessible(true);
Ignore ignore = field.getAnnotation(Ignore.class);
if (ignore != null && ignore.value()) {
continue;
}
Class<?> type = field.getType();
int column = cursor.getColumnIndex(field.getName());
if (type == String.class) {
field.set(entity, cursor.getString(column));
} else if (type == int.class || type == Integer.class) {
field.setInt(entity, cursor.getInt(column));
} else if (type == float.class || type == Float.class) {
field.setFloat(entity, cursor.getFloat(column));
} else if (type == double.class || type == Double.class) {
field.setDouble(entity, cursor.getDouble(column));
} else if (type == long.class || type == Long.class) {
field.setLong(entity, cursor.getLong(column));
} else if (type == boolean.class || type == Boolean.class) {
field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false"));
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
field.set(entity, new Date(cursor.getString(column)));
} else if (type == byte[].class) {
field.set(entity, cursor.getBlob(column));
}
// field.set(entity, cursor.getColumnIndex("entity_id"));
}
entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid"));
entitys.add(entity);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
cursor.close();
return entitys;
}
}

@ -0,0 +1,330 @@
package com.arialyy.downloadutil.orm;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.util.Log;
import com.arialyy.downloadutil.util.Util;
import java.lang.reflect.Field;
/**
* Created by AriaLyy on 2015/2/11.
* 数据库操作工具
*/
public class DbUtil {
private static final String TAG = "DbUtil";
private volatile static DbUtil mDbUtil = null;
private int CREATE_TABLE = 0;
private int TABLE_EXISTS = 1;
private int INSERT_DATA = 2;
private int MODIFY_DATA = 3;
private int FIND_DATA = 4;
private int FIND_ALL_DATA = 5;
private int DEL_DATA = 6;
private int ROW_ID = 7;
private static final Object LOCK = new Object();
private SQLiteDatabase mDb;
private DbUtil() {
}
private DbUtil(SQLiteDatabase db) {
mDb = db;
}
protected static DbUtil getInstance(SQLiteDatabase db) {
if (mDbUtil == null) {
synchronized (LOCK) {
if (mDbUtil == null) {
mDbUtil = new DbUtil(db);
}
}
}
return mDbUtil;
}
/**
* 删除某条数据
*/
protected void delData(DbEntity dbEntity, @NonNull Object[] wheres, @NonNull Object[] values) {
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "输入删除条件");
return;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("DELETE FROM ").append(Util.getClassName(dbEntity)).append(" WHERE ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ",");
i++;
}
print(DEL_DATA, sb.toString());
mDb.execSQL(sb.toString());
}
/**
* 修改某行数据
*/
protected void modifyData(DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(Util.getClassName(dbEntity)).append(" SET ");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
Ignore ignore = field.getAnnotation(Ignore.class);
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
try {
sb.append(field.getName()).append(" = '").append(field.get(dbEntity).toString()).append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
print(MODIFY_DATA, sb.toString());
mDb.execSQL(sb.toString());
}
}
/**
* 遍历所有数据
*/
protected Cursor findAllData(DbEntity dbEntity) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(dbEntity));
print(FIND_ALL_DATA, sb.toString());
return mDb.rawQuery(sb.toString(), null);
}
/**
* 条件查寻数据
*/
protected Cursor findData(DbEntity dbEntity, @NonNull Object[] wheres, @NonNull Object[] values) {
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "请输入查询条件");
return null;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(dbEntity)).append(" where ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ", ");
i++;
}
print(FIND_DATA, sb.toString());
return mDb.rawQuery(sb.toString(), null);
}
/**
* 插入数据
*/
protected void insertData(DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(Util.getClassName(dbEntity)).append("(");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
Ignore ignore = field.getAnnotation(Ignore.class);
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(field.getName());
i++;
}
sb.append(") VALUES (");
i = 0;
for (Field field : fields) {
field.setAccessible(true);
Ignore ignore = field.getAnnotation(Ignore.class);
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append("'");
try {
sb.append(field.get(dbEntity)).append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
sb.append(")");
print(INSERT_DATA, sb.toString());
mDb.execSQL(sb.toString());
}
}
/**
* 查找某张表是否存在
*/
protected boolean tableExists(DbEntity dbEntity) {
Cursor cursor = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='");
sb.append(Util.getClassName(dbEntity));
sb.append("'");
print(TABLE_EXISTS, sb.toString());
cursor = mDb.rawQuery(sb.toString(), null);
if (cursor != null && cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return false;
}
/**
* 创建表
*
* @param dbEntity
*/
protected void createTable(DbEntity dbEntity) {
Field[] fields = Util.getFields(dbEntity.getClass());
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("create table ")
.append(Util.getClassName(dbEntity))
.append("(");
int i = 0;
int ignoreNum = 0;
for (Field field : fields) {
i++;
field.setAccessible(true);
Ignore ignore = field.getAnnotation(Ignore.class);
if (ignore != null && ignore.value()) {
ignoreNum++;
continue;
}
sb.append(field.getName());
Class<?> type = field.getType();
if (type == String.class) {
sb.append(" varchar");
} else if (type == int.class || type == Integer.class) {
sb.append(" interger");
} else if (type == float.class || type == Float.class) {
sb.append(" float");
} else if (type == double.class || type == Double.class) {
sb.append(" double");
} else if (type == long.class || type == Long.class) {
sb.append(" bigint");
} else if (type == boolean.class || type == Boolean.class) {
sb.append(" boolean");
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
sb.append(" data");
} else {
sb.append(" blob");
}
sb.append(i >= fields.length - ignoreNum - 1 ? "" : ", ");
}
sb.append(");");
print(CREATE_TABLE, sb.toString());
mDb.execSQL(sb.toString());
}
}
/**
* 打印数据库日志
*
* @param type {@link DbUtil}
* @param sql
*/
private void print(int type, String sql) {
String str = "";
switch (type) {
case 0:
str = "创建表 >>>> ";
break;
case 1:
str = "表是否存在 >>>> ";
break;
case 2:
str = "插入数据 >>>> ";
break;
case 3:
str = "修改数据 >>>> ";
break;
case 4:
str = "查询一行数据 >>>> ";
break;
case 5:
str = "遍历整个数据库 >>>> ";
break;
}
Log.v(TAG, str + sql);
}
/**
* 关闭数据库
*/
protected void close() {
if (mDb != null) {
mDb.close();
}
}
/**
* 获取所有行Id
*/
protected Cursor getRowId(DbEntity dbEntity) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(dbEntity));
return mDb.rawQuery(sb.toString(), null);
}
/**
* 获取行Id
*
* @return
*/
protected int getRowId(DbEntity dbEntity, Object[] wheres, Object[] values) {
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "请输入删除条件");
return -1;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return -1;
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid FROM ").append(Util.getClassName(dbEntity)).append(" WHERE ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ",");
i++;
}
print(ROW_ID, sb.toString());
Cursor c = mDb.rawQuery(sb.toString(), null);
int id = c.getColumnIndex("rowid");
c.close();
return id;
}
}

@ -0,0 +1,16 @@
package com.arialyy.downloadutil.orm;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by lyy on 2015/11/2.
* 表ID字段指定
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
int value() default -1;
}

@ -0,0 +1,16 @@
package com.arialyy.downloadutil.orm;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by lyy on 2015/11/2.
* 忽略某个字段
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ignore {
boolean value() default false;
}

@ -0,0 +1,38 @@
package com.arialyy.downloadutil.orm;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
/**
* Created by lyy on 2015/11/2.
* sql帮助类
*/
public class SqlHelper extends SQLiteOpenHelper {
protected static String DB_NAME;
protected static int VERSION = -1;
static {
if (TextUtils.isEmpty(DB_NAME)) {
DB_NAME = "AriaLyyDb";
}
if (VERSION == -1) {
VERSION = 1;
}
}
public SqlHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

@ -1,163 +1,163 @@
package com.arialyy.downloadutil.util;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import com.arialyy.downloadutil.entity.DownloadEntity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lyy on 2016/8/11.
* 数据库帮助类
*/
public class SQLHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "ARIA_LYY_DB";
public static final String TABLE_NAME = "ARIA_LYY_DOWNLOAD";
public SQLHelper(Context context) {
this(context, DB_NAME, null, 1);
}
private SQLHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE_NAME + "(" +
"url varchar PRIMARY KEY, " +
"path varchar, " +
"completeTime interger, " +
"fileSize interger, " +
"state smallint , " +
"isDownloadComplete smallint, " +
"currentProgress interger" +
")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* 获取所有下载实体
*/
public List<DownloadEntity> getAllEntity(@NonNull SQLiteDatabase db) {
List<DownloadEntity> list = new ArrayList<>();
Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null);
if (c.moveToFirst()) {
while (c.moveToNext()) {
list.add(cursor2Entity(c));
}
}
c.close();
return list;
}
/**
* 更新下载实体
*/
public void updateEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) {
String whereClause = "url=?";
String[] whereArgs = {entity.getDownloadUrl()};
db.update(TABLE_NAME, createCv(entity), whereClause, whereArgs);
}
/**
* 删除下载实体
*/
public void delEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) {
delEntity(db, entity.getDownloadUrl());
}
/**
* 通过下载链接删除下载实体
*/
public void delEntity(@NonNull SQLiteDatabase db, String downloadUrl) {
String whereClause = "url=?";
String[] whereArgs = {downloadUrl};
db.delete(TABLE_NAME, whereClause, whereArgs);
}
/**
* 通过下载链接查找下载实体
*
* @param downloadUrl
* @return
*/
public DownloadEntity findEntity(@NonNull SQLiteDatabase db, @NonNull String downloadUrl) {
DownloadEntity entity;
String sql = "select * from " + TABLE_NAME + "where url=?";
Cursor c = db.rawQuery(sql, new String[]{downloadUrl});
if (c.getCount() <= 0) {
c.close();
return null;
} else {
c.moveToFirst();
entity = cursor2Entity(c);
}
c.close();
return entity;
}
/**
* 存储下载实体
*
* @param entity
*/
public void savaEntity(@NonNull SQLiteDatabase db, @NonNull DownloadEntity entity) {
DownloadEntity temp = findEntity(db, entity.getDownloadUrl());
if (temp == null) {
db.insert(TABLE_NAME, null, createCv(entity));
} else {
updateEntity(db, entity);
}
}
/**
* 游标转实体
*
* @param c
* @return
*/
private DownloadEntity cursor2Entity(Cursor c) {
DownloadEntity entity;
entity = new DownloadEntity();
entity.setDownloadUrl(c.getString(c.getColumnIndex("url")));
entity.setDownloadPath(c.getString(c.getColumnIndex("path")));
entity.setCompleteTime(c.getLong(c.getColumnIndex("completeTime")));
entity.setFileSize(c.getLong(c.getColumnIndex("fileSize")));
entity.setState(c.getInt(c.getColumnIndex("state")));
// 0 ==> false, 1 ==> true
entity.setDownloadComplete(c.getInt(c.getColumnIndex("isDownloadComplete")) == 0);
entity.setCurrentProgress(c.getLong(c.getColumnIndex("currentProgress")));
return entity;
}
/**
* 创建ContentValues
*
* @param entity
* @return
*/
private ContentValues createCv(@NonNull DownloadEntity entity) {
ContentValues cv = new ContentValues();
cv.put("url", entity.getDownloadUrl());
cv.put("path", entity.getDownloadPath());
cv.put("completeTime", entity.getCompleteTime());
cv.put("fileSize", entity.getFileSize());
cv.put("state", entity.getState());
// 0 ==> false, 1 ==> true
cv.put("isDownloadComplete", entity.isDownloadComplete() ? 1 : 0);
cv.put("currentProgress", entity.getCurrentProgress());
return cv;
}
}
//package com.arialyy.downloadutil.util;
//
//import android.content.ContentValues;
//import android.content.Context;
//import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteOpenHelper;
//import android.support.annotation.NonNull;
//
//import com.arialyy.downloadutil.entity.DownloadEntity;
//
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by lyy on 2016/8/11.
// * 数据库帮助类
// */
//public class SQLHelper extends SQLiteOpenHelper {
// public static final String DB_NAME = "ARIA_LYY_DB";
// public static final String TABLE_NAME = "ARIA_LYY_DOWNLOAD";
//
// public SQLHelper(Context context) {
// this(context, DB_NAME, null, 1);
// }
//
// private SQLHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// String sql = "create table " + TABLE_NAME + "(" +
// "url varchar PRIMARY KEY, " +
// "path varchar, " +
// "completeTime interger, " +
// "fileSize interger, " +
// "state smallint , " +
// "isDownloadComplete smallint, " +
// "currentProgress interger" +
// ")";
// db.execSQL(sql);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
// }
//
// /**
// * 获取所有下载实体
// */
// public List<DownloadEntity> getAllEntity(@NonNull SQLiteDatabase db) {
// List<DownloadEntity> list = new ArrayList<>();
// Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null);
// if (c.moveToFirst()) {
// while (c.moveToNext()) {
// list.add(cursor2Entity(c));
// }
// }
// c.close();
// return list;
// }
//
// /**
// * 更新下载实体
// */
// public void updateEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) {
// String whereClause = "url=?";
// String[] whereArgs = {entity.getDownloadUrl()};
// db.update(TABLE_NAME, createCv(entity), whereClause, whereArgs);
// }
//
// /**
// * 删除下载实体
// */
// public void delEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) {
// delEntity(db, entity.getDownloadUrl());
// }
//
// /**
// * 通过下载链接删除下载实体
// */
// public void delEntity(@NonNull SQLiteDatabase db, String downloadUrl) {
// String whereClause = "url=?";
// String[] whereArgs = {downloadUrl};
// db.delete(TABLE_NAME, whereClause, whereArgs);
// }
//
// /**
// * 通过下载链接查找下载实体
// *
// * @param downloadUrl
// * @return
// */
// public DownloadEntity findEntity(@NonNull SQLiteDatabase db, @NonNull String downloadUrl) {
// DownloadEntity entity;
// String sql = "select * from " + TABLE_NAME + "where url=?";
// Cursor c = db.rawQuery(sql, new String[]{downloadUrl});
// if (c.getCount() <= 0) {
// c.close();
// return null;
// } else {
// c.moveToFirst();
// entity = cursor2Entity(c);
// }
// c.close();
// return entity;
// }
//
// /**
// * 存储下载实体
// *
// * @param entity
// */
// public void savaEntity(@NonNull SQLiteDatabase db, @NonNull DownloadEntity entity) {
// DownloadEntity temp = findEntity(db, entity.getDownloadUrl());
// if (temp == null) {
// db.insert(TABLE_NAME, null, createCv(entity));
// } else {
// updateEntity(db, entity);
// }
// }
//
// /**
// * 游标转实体
// *
// * @param c
// * @return
// */
// private DownloadEntity cursor2Entity(Cursor c) {
// DownloadEntity entity;
// entity = new DownloadEntity();
// entity.setDownloadUrl(c.getString(c.getColumnIndex("url")));
// entity.setDownloadPath(c.getString(c.getColumnIndex("path")));
// entity.setCompleteTime(c.getLong(c.getColumnIndex("completeTime")));
// entity.setFileSize(c.getLong(c.getColumnIndex("fileSize")));
// entity.setState(c.getInt(c.getColumnIndex("state")));
// // 0 ==> false, 1 ==> true
// entity.setDownloadComplete(c.getInt(c.getColumnIndex("isDownloadComplete")) == 0);
// entity.setCurrentProgress(c.getLong(c.getColumnIndex("currentProgress")));
// return entity;
// }
//
// /**
// * 创建ContentValues
// *
// * @param entity
// * @return
// */
// private ContentValues createCv(@NonNull DownloadEntity entity) {
// ContentValues cv = new ContentValues();
// cv.put("url", entity.getDownloadUrl());
// cv.put("path", entity.getDownloadPath());
// cv.put("completeTime", entity.getCompleteTime());
// cv.put("fileSize", entity.getFileSize());
// cv.put("state", entity.getState());
// // 0 ==> false, 1 ==> true
// cv.put("isDownloadComplete", entity.isDownloadComplete() ? 1 : 0);
// cv.put("currentProgress", entity.getCurrentProgress());
// return cv;
// }
//}

@ -8,6 +8,7 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Properties;
@ -17,6 +18,32 @@ import java.util.Properties;
public class Util {
private static final String TAG = "util";
/**
* 获取类里面的所在字段
*/
public static Field[] getFields(Class clazz) {
Field[] fields = null;
fields = clazz.getDeclaredFields();
if (fields == null || fields.length == 0) {
Class superClazz = clazz.getSuperclass();
if (superClazz != null) {
fields = getFields(superClazz);
}
}
return fields;
}
/**
* 获取对象名
*
* @param obj 对象
* @return 对象名
*/
public static String getClassName(Object obj) {
String arrays[] = obj.getClass().getName().split("\\.");
return arrays[arrays.length - 1];
}
/**
* 格式化文件大小
*
@ -49,6 +76,7 @@ public class Util {
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
/**
* 创建目录 当目录不存在的时候创建文件否则返回false
*
@ -96,6 +124,7 @@ public class Util {
}
return null;
}
/**
* 设置打印的异常格式
*/
@ -122,6 +151,7 @@ public class Util {
err.append("===================================================");
return err.toString();
}
/**
* 读取下载配置文件
*
@ -129,8 +159,8 @@ public class Util {
* @return
*/
public static Properties loadConfig(File file) {
Properties properties = new Properties();
FileInputStream fis = null;
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
properties.load(fis);

Loading…
Cancel
Save