完善下载

This commit is contained in:
lyy
2016-10-07 19:30:55 +08:00
parent cb9188423f
commit 9c2015c90b
23 changed files with 337 additions and 93 deletions

View File

@ -8,6 +8,7 @@ import com.arialyy.downloadutil.core.command.IDownloadCommand;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.orm.DbEntity;
import com.arialyy.downloadutil.orm.DbUtil;
import com.arialyy.downloadutil.util.Task;
import java.util.ArrayList;
import java.util.List;
@ -63,7 +64,7 @@ public class DownloadManager {
/**
* 下载实体
*/
public static final String DATA = "DOWNLOAD_ENTITY";
public static final String ENTITY = "DOWNLOAD_ENTITY";
/**
* 位置

View File

@ -48,8 +48,13 @@ public class DownloadTarget extends IDownloadTarget {
}
@Override public void stopTask(Task task) {
if (mExecutePool.removeTask(task)) {
if (task.isDownloading()) {
if (mExecutePool.removeTask(task)) {
task.stop();
}
}else {
task.stop();
Log.w(TAG, "停止任务失败,【任务已经停止】");
}
}

View File

@ -98,6 +98,14 @@ public abstract class IDownloadTarget implements IDownloader, ITask {
this.mTargetListener = targetListener;
}
/**
* 获取任务执行池
* @return
*/
public ExecutePool getExecutePool(){
return mExecutePool;
}
/**
* 获取当前运行的任务数
*

View File

@ -3,8 +3,8 @@ package com.arialyy.downloadutil.core.command;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/**
* Created by lyy on 2016/9/20.
@ -22,10 +22,15 @@ class StopCommand extends IDownloadCommand {
@Override public void executeComment() {
Task task = target.getTask(mEntity);
if (task != null) {
target.stopTask(task);
if (task == null) {
if (mEntity.getState() == DownloadEntity.STATE_DOWNLOAD_ING) {
task = target.createTask(mEntity);
target.stopTask(task);
} else {
Log.w(TAG, "停止命令执行失败,【调度器中没有该任务】");
}
} else {
Log.w(TAG, "停止命令执行失败,【调度器中没有该任务】");
target.stopTask(task);
}
}
}

View File

@ -23,7 +23,7 @@ public class DbEntity {
/**
* 获取所有行的rowid
*/
public int[] getRowId() {
public int[] getRowIds() {
return mUtil.getRowId(getClass());
}
@ -71,6 +71,18 @@ public class DbEntity {
* 查找数据在表中是否存在
*/
private boolean thisIsExist() {
return findData(getClass(), new String[]{"rowid"}, new String[]{rowID + ""}) != null;
}
/**
* 插入数据
*/
public void insert() {
mUtil.insertData(this);
updateRowID();
}
private void updateRowID() {
try {
Field[] fields = Util.getFields(getClass());
List<String> where = new ArrayList<>();
@ -84,19 +96,14 @@ public class DbEntity {
where.add(field.getName());
values.add(field.get(this) + "");
}
return findData(getClass(), where.toArray(new String[where.size()]),
values.toArray(new String[values.size()])) != null;
DbEntity entity = findData(getClass(), where.toArray(new String[where.size()]),
values.toArray(new String[values.size()]));
if (entity != null) {
rowID = entity.rowID;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return false;
}
/**
* 插入数据
*/
public void insert() {
mUtil.insertData(this);
}
/**

View File

@ -62,7 +62,7 @@ public class DbUtil {
/**
* 删除某条数据
*/
protected <T extends DbEntity> void delData(Class<T> clazz, @NonNull Object[] wheres,
<T extends DbEntity> void delData(Class<T> clazz, @NonNull Object[] wheres,
@NonNull Object[] values) {
mDb = mHelper.getWritableDatabase();
if (wheres.length <= 0 || values.length <= 0) {
@ -88,7 +88,7 @@ public class DbUtil {
/**
* 修改某行数据
*/
protected void modifyData(DbEntity dbEntity) {
void modifyData(DbEntity dbEntity) {
mDb = mHelper.getWritableDatabase();
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
@ -105,7 +105,7 @@ public class DbUtil {
sb.append(i > 0 ? ", " : "");
try {
sb.append(field.getName())
.append(" = '")
.append("='")
.append(field.get(dbEntity).toString())
.append("'");
} catch (IllegalAccessException e) {
@ -113,6 +113,7 @@ public class DbUtil {
}
i++;
}
sb.append(" where rowid=").append(dbEntity.rowID);
print(MODIFY_DATA, sb.toString());
mDb.execSQL(sb.toString());
}
@ -122,7 +123,10 @@ public class DbUtil {
/**
* 遍历所有数据
*/
protected <T extends DbEntity> List<T> findAllData(Class<T> clazz) {
<T extends DbEntity> List<T> findAllData(Class<T> clazz) {
if (!tableExists(clazz)) {
createTable(clazz);
}
mDb = mHelper.getReadableDatabase();
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(clazz));
@ -134,7 +138,7 @@ public class DbUtil {
/**
* 条件查寻数据
*/
protected <T extends DbEntity> List<T> findData(Class<T> clazz, @NonNull String[] wheres,
<T extends DbEntity> List<T> findData(Class<T> clazz, @NonNull String[] wheres,
@NonNull String[] values) {
if (!tableExists(clazz)) {
createTable(clazz);
@ -163,7 +167,7 @@ public class DbUtil {
/**
* 插入数据
*/
protected void insertData(DbEntity dbEntity) {
void insertData(DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
if (!tableExists(clazz)) {
createTable(clazz);
@ -211,14 +215,14 @@ public class DbUtil {
/**
* 查找某张表是否存在
*/
public synchronized boolean tableExists(Class clazz) {
synchronized boolean tableExists(Class clazz) {
if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getReadableDatabase();
}
Cursor cursor = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='");
sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='");
sb.append(Util.getClassName(clazz));
sb.append("'");
print(TABLE_EXISTS, sb.toString());
@ -326,7 +330,7 @@ public class DbUtil {
/**
* 获取所在行Id
*/
protected int[] getRowId(Class clazz) {
int[] getRowId(Class clazz) {
mDb = mHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT rowid, * FROM " + Util.getClassName(clazz), null);
int[] ids = new int[cursor.getCount()];
@ -343,7 +347,7 @@ public class DbUtil {
/**
* 获取行Id
*/
protected int getRowId(Class clazz, Object[] wheres, Object[] values) {
int getRowId(Class clazz, Object[] wheres, Object[] values) {
mDb = mHelper.getReadableDatabase();
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "请输入删除条件");
@ -404,7 +408,6 @@ public class DbUtil {
} 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);

View File

@ -55,6 +55,16 @@ public class Task {
public void stop() {
if (mUtil.isDownloading()) {
mUtil.stopDownload();
} else {
mEntity.setState(DownloadEntity.STATE_STOP);
mEntity.save();
sendInState2Target(IDownloadTarget.STOP);
// 发送停止下载的广播
Intent intent = createIntent(DownloadManager.ACTION_STOP);
intent.putExtra(DownloadManager.CURRENT_LOCATION, mEntity.getCurrentProgress());
intent.putExtra(DownloadManager.ENTITY, mEntity);
mContext.sendBroadcast(intent);
}
}
@ -84,40 +94,61 @@ public class Task {
mUtil.delConfigFile();
mUtil.delTempFile();
mEntity.deleteData();
sendInState2Target(IDownloadTarget.CANCEL);
//发送取消下载的广播
Uri.Builder builder = new Uri.Builder();
builder.scheme(mContext.getPackageName());
Uri uri = builder.build();
Intent intent = new Intent(DownloadManager.ACTION_CANCEL);
intent.setData(uri);
intent.putExtra(DownloadManager.ACTION_CANCEL, mEntity);
Intent intent = createIntent(DownloadManager.ACTION_CANCEL);
intent.putExtra(DownloadManager.ENTITY, mEntity);
mContext.sendBroadcast(intent);
}
}
/**
* 创建特定的Intent
*
* @param action
* @return
*/
private Intent createIntent(String action) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(mContext.getPackageName());
Uri uri = builder.build();
Intent intent = new Intent(action);
intent.setData(uri);
return intent;
}
/**
* 将任务状态发送给下载器
*
* @param state {@link IDownloadTarget#START}
*/
private void sendInState2Target(int state) {
if (mOutHandler != null) {
mOutHandler.obtainMessage(state, mEntity).sendToTarget();
}
}
/**
* 下载监听类
*/
private static class DownloadListener extends DownLoadUtil.DownloadListener {
private class DownloadListener extends DownLoadUtil.DownloadListener {
Handler outHandler;
Context context;
Intent sendIntent;
long INTERVAL = 1024 * 10; //10k大小的间隔
long lastLen = 0; //上一次发送长度
long lastTime = 0;
long INTERVAL_TIME = 60 * 1000; //10k大小的间隔
DownloadEntity downloadEntity;
public DownloadListener(Context context, DownloadEntity downloadEntity,
DownloadListener(Context context, DownloadEntity downloadEntity,
Handler outHandler) {
this.context = context;
this.outHandler = outHandler;
this.downloadEntity = downloadEntity;
sendIntent = new Intent(DownloadManager.ACTION_RUNNING);
Uri.Builder builder = new Uri.Builder();
builder.scheme(context.getPackageName());
Uri uri = builder.build();
sendIntent.setData(uri);
sendIntent = createIntent(DownloadManager.ACTION_RUNNING);
sendIntent.putExtra(DownloadManager.ENTITY, downloadEntity);
}
@Override public void onPreDownload(HttpURLConnection connection) {
@ -143,9 +174,14 @@ public class Task {
@Override public void onProgress(long currentLocation) {
super.onProgress(currentLocation);
if (currentLocation - lastLen > INTERVAL) { //不要太过于频繁发送广播
sendIntent.putExtra(DownloadManager.ACTION_RUNNING, currentLocation);
lastLen = currentLocation;
// if (currentLocation - lastLen > INTERVAL) { //不要太过于频繁发送广播
// sendIntent.putExtra(DownloadManager.CURRENT_LOCATION, currentLocation);
// lastLen = currentLocation;
// context.sendBroadcast(sendIntent);
// }
if (System.currentTimeMillis() - lastLen > INTERVAL_TIME){
sendIntent.putExtra(DownloadManager.CURRENT_LOCATION, currentLocation);
lastTime = System.currentTimeMillis();
context.sendBroadcast(sendIntent);
}
}
@ -180,27 +216,12 @@ public class Task {
sendIntent(DownloadManager.ACTION_FAIL, -1);
}
/**
* 将任务状态发送给下载器
*
* @param state {@link IDownloadTarget#START}
*/
private void sendInState2Target(int state) {
if (outHandler != null) {
outHandler.obtainMessage(state, downloadEntity).sendToTarget();
}
}
private void sendIntent(String action, long location) {
downloadEntity.setDownloadComplete(action.equals(DownloadManager.ACTION_COMPLETE));
downloadEntity.setCurrentProgress(location);
downloadEntity.update();
Uri.Builder builder = new Uri.Builder();
builder.scheme(context.getPackageName());
Uri uri = builder.build();
Intent intent = new Intent(action);
intent.setData(uri);
intent.putExtra(action, downloadEntity);
Intent intent = createIntent(action);
intent.putExtra(DownloadManager.ENTITY, downloadEntity);
if (location != -1) {
intent.putExtra(DownloadManager.CURRENT_LOCATION, location);
}

View File

@ -58,7 +58,24 @@ public class Util {
}
/**
* 将缓存的key转换为hash码
* 字符串转hashcode
*
* @param str
* @return
*/
public static int keyToHashCode(String str) {
int total = 0;
for (int i = 0; i < str.length() && i < 6; i++) {
char ch = str.charAt(i);
if (ch == '-') ch = (char) 28; // does not contain the same last 5 bits as any letter
if (ch == '\'') ch = (char) 29; // nor this
total = (total * 33) + (ch & 0x1F);
}
return total;
}
/**
* 将key转换为16进制码
*
* @param key 缓存的key
* @return 转换后的key的值, 系统便是通过该key来读写缓存