大量bug修复,单任务下载例子编写

This commit is contained in:
lyy
2016-10-06 20:41:34 +08:00
parent 97d7a3e3ae
commit 7a962edeae
22 changed files with 268 additions and 137 deletions

View File

@ -1,6 +1,5 @@
package com.arialyy.simple.activity; package com.arialyy.simple.activity;
import android.Manifest;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -19,10 +18,8 @@ import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.core.command.CommandFactory; import com.arialyy.downloadutil.core.command.CommandFactory;
import com.arialyy.downloadutil.core.command.IDownloadCommand; import com.arialyy.downloadutil.core.command.IDownloadCommand;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.DownLoadUtil; import com.arialyy.downloadutil.orm.DbEntity;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
import com.arialyy.frame.permission.OnPermissionCallback;
import com.arialyy.frame.permission.PermissionManager;
import com.arialyy.frame.util.show.L; import com.arialyy.frame.util.show.L;
import com.arialyy.simple.R; import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity; import com.arialyy.simple.base.BaseActivity;
@ -43,10 +40,12 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
private static final int DOWNLOAD_COMPLETE = 0x06; private static final int DOWNLOAD_COMPLETE = 0x06;
private ProgressBar mPb; private ProgressBar mPb;
private String mDownloadUrl = "http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk"; private String mDownloadUrl = "http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk";
private DownLoadUtil mUtil;
private Button mStart, mStop, mCancel; private Button mStart, mStop, mCancel;
private TextView mSize; private TextView mSize;
@Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.toolbar) Toolbar toolbar;
private CommandFactory mFactory;
private DownloadManager mManager;
private DownloadEntity mEntity;
private Handler mUpdateHandler = new Handler() { private Handler mUpdateHandler = new Handler() {
@Override public void handleMessage(Message msg) { @Override public void handleMessage(Message msg) {
@ -78,6 +77,7 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
break; break;
case DOWNLOAD_COMPLETE: case DOWNLOAD_COMPLETE:
Toast.makeText(SimpleTestActivity.this, "下载完成", Toast.LENGTH_SHORT).show(); Toast.makeText(SimpleTestActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
mStart.setText("重新开始");
mStart.setEnabled(true); mStart.setEnabled(true);
mCancel.setEnabled(false); mCancel.setEnabled(false);
mStop.setEnabled(false); mStop.setEnabled(false);
@ -96,12 +96,15 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
DownloadEntity entity = intent.getParcelableExtra(DownloadManager.ACTION_PRE); DownloadEntity entity = intent.getParcelableExtra(DownloadManager.ACTION_PRE);
len = entity.getFileSize(); len = entity.getFileSize();
L.d(TAG, "download pre"); L.d(TAG, "download pre");
mUpdateHandler.obtainMessage(DOWNLOAD_PRE, len).sendToTarget();
break; break;
case DownloadManager.ACTION_START: case DownloadManager.ACTION_START:
L.d(TAG, "download start"); L.d(TAG, "download start");
break; break;
case DownloadManager.ACTION_RESUME: case DownloadManager.ACTION_RESUME:
L.d(TAG, "download resume"); L.d(TAG, "download resume");
long location = intent.getLongExtra(DownloadManager.CURRENT_LOCATION, 1);
mUpdateHandler.obtainMessage(DOWNLOAD_RESUME, location).sendToTarget();
break; break;
case DownloadManager.ACTION_RUNNING: case DownloadManager.ACTION_RUNNING:
long current = intent.getLongExtra(DownloadManager.ACTION_RUNNING, 0); long current = intent.getLongExtra(DownloadManager.ACTION_RUNNING, 0);
@ -113,6 +116,16 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
break; break;
case DownloadManager.ACTION_STOP: case DownloadManager.ACTION_STOP:
L.d(TAG, "download stop"); L.d(TAG, "download stop");
mUpdateHandler.sendEmptyMessage(DOWNLOAD_STOP);
break;
case DownloadManager.ACTION_COMPLETE:
mUpdateHandler.sendEmptyMessage(DOWNLOAD_COMPLETE);
break;
case DownloadManager.ACTION_CANCEL:
mUpdateHandler.sendEmptyMessage(DOWNLOAD_CANCEL);
break;
case DownloadManager.ACTION_FAIL:
mUpdateHandler.sendEmptyMessage(DOWNLOAD_FAILE);
break; break;
} }
} }
@ -141,6 +154,7 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
super.init(savedInstanceState); super.init(savedInstanceState);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
init(); init();
} }
private void init() { private void init() {
@ -149,7 +163,16 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
mStop = (Button) findViewById(R.id.stop); mStop = (Button) findViewById(R.id.stop);
mCancel = (Button) findViewById(R.id.cancel); mCancel = (Button) findViewById(R.id.cancel);
mSize = (TextView) findViewById(R.id.size); mSize = (TextView) findViewById(R.id.size);
mUtil = new DownLoadUtil(); mFactory = CommandFactory.getInstance();
mManager = DownloadManager.getInstance();
mEntity = DbEntity.findData(DownloadEntity.class, new String[]{"downloadUrl"},
new String[]{mDownloadUrl});
if (mEntity != null) {
mPb.setProgress((int) ((mEntity.getCurrentProgress() * 100) / mEntity.getFileSize()));
mSize.setText(Util.formatFileSize(mEntity.getFileSize()));
} else {
mEntity = new DownloadEntity();
}
} }
public void onClick(View view) { public void onClick(View view) {
@ -181,30 +204,29 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
} }
} }
DownloadEntity entity = new DownloadEntity();
private void start() { private void start() {
entity.setFileName("test.apk"); mEntity.setFileName("test.apk");
entity.setDownloadUrl(mDownloadUrl); mEntity.setDownloadUrl(mDownloadUrl);
entity.setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/test.apk"); mEntity.setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/test.apk");
List<IDownloadCommand> commands = new ArrayList<>(); List<IDownloadCommand> commands = new ArrayList<>();
IDownloadCommand addCommand = CommandFactory.getInstance() IDownloadCommand addCommand = mFactory.createCommand(this, mEntity,
.createCommand(this, entity, CommandFactory.TASK_CREATE); CommandFactory.TASK_CREATE);
IDownloadCommand startCommand = CommandFactory.getInstance() IDownloadCommand startCommand = mFactory.createCommand(this, mEntity,
.createCommand(this, entity, CommandFactory.TASK_START); CommandFactory.TASK_START);
commands.add(addCommand); commands.add(addCommand);
commands.add(startCommand); commands.add(startCommand);
DownloadManager.getInstance().setCommands(commands).exe(); mManager.setCommands(commands).exe();
} }
private void stop() { private void stop() {
// mUtil.stopDownload(); IDownloadCommand stopCommand = mFactory.createCommand(this, mEntity,
IDownloadCommand stopCommand = CommandFactory.getInstance() CommandFactory.TASK_STOP);
.createCommand(this, entity, CommandFactory.TASK_STOP); mManager.setCommand(stopCommand).exe();
DownloadManager.getInstance().setCommand(stopCommand).exe();
} }
private void cancel() { private void cancel() {
mUtil.cancelDownload(); IDownloadCommand cancelCommand = mFactory.createCommand(this, mEntity,
CommandFactory.TASK_CANCEL);
mManager.setCommand(cancelCommand).exe();
} }
} }

View File

@ -5,6 +5,8 @@ import android.content.Context;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.command.IDownloadCommand; 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.orm.DbUtil;
import java.util.ArrayList; import java.util.ArrayList;
@ -102,6 +104,10 @@ public class DownloadManager {
return INSTANCE; return INSTANCE;
} }
public List<DownloadEntity> getAllDownloadEntity(){
return DbEntity.findAllData(DownloadEntity.class);
}
/** /**
* 设置命令 * 设置命令
*/ */

View File

@ -4,6 +4,7 @@ import android.content.Context;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/** /**
* Created by lyy on 2016/8/17. * Created by lyy on 2016/8/17.
@ -53,13 +54,13 @@ public class DownloadTarget extends IDownloadTarget {
} }
@Override public void cancelTask(Task task) { @Override public void cancelTask(Task task) {
if (mExecutePool.removeTask(task)) { if (mExecutePool.removeTask(task) || mCachePool.removeTask(task)) {
task.cancel(); task.cancel();
} }
} }
@Override public void reTryStart(Task task) { @Override public void reTryStart(Task task) {
if (!task.getDownloadUtil().isDownloading()) { if (!task.isDownloading()) {
task.start(); task.start();
} else { } else {
Log.w(TAG, "任务没有完全停止,重试下载失败"); Log.w(TAG, "任务没有完全停止,重试下载失败");
@ -77,9 +78,6 @@ public class DownloadTarget extends IDownloadTarget {
if (task == null) { if (task == null) {
task = mCachePool.getTask(entity.getDownloadUrl()); task = mCachePool.getTask(entity.getDownloadUrl());
} }
if (task == null) {
task = createTask(entity);
}
return task; return task;
} }

View File

@ -9,6 +9,7 @@ import com.arialyy.downloadutil.core.inf.ITask;
import com.arialyy.downloadutil.core.pool.CachePool; import com.arialyy.downloadutil.core.pool.CachePool;
import com.arialyy.downloadutil.core.pool.ExecutePool; import com.arialyy.downloadutil.core.pool.ExecutePool;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/** /**
* Created by lyy on 2016/8/16. * Created by lyy on 2016/8/16.
@ -210,7 +211,7 @@ public abstract class IDownloadTarget implements IDownloader, ITask {
target.removeTask(entity); target.removeTask(entity);
Task newTask = target.getNextTask(); Task newTask = target.getNextTask();
if (newTask == null) { if (newTask == null) {
Log.e(TAG, "没有下一任务"); Log.w(TAG, "没有下一任务");
return; return;
} }
target.startTask(newTask); target.startTask(newTask);

View File

@ -4,6 +4,7 @@ import android.content.Context;
import android.os.Handler; import android.os.Handler;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/** /**
* Created by lyy on 2016/8/18. * Created by lyy on 2016/8/18.
@ -37,6 +38,6 @@ public class TaskFactory {
public Task createTask(Context context, DownloadEntity entity, Handler handler) { public Task createTask(Context context, DownloadEntity entity, Handler handler) {
Task.Builder builder = new Task.Builder(context, entity); Task.Builder builder = new Task.Builder(context, entity);
builder.setOutHandler(handler); builder.setOutHandler(handler);
return builder.builder(); return builder.build();
} }
} }

View File

@ -1,7 +1,9 @@
package com.arialyy.downloadutil.core.command; package com.arialyy.downloadutil.core.command;
import android.content.Context; import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -15,6 +17,11 @@ class AddCommand extends IDownloadCommand {
} }
@Override public void executeComment() { @Override public void executeComment() {
Task task = target.getTask(mEntity);
if (task == null) {
target.createTask(mEntity); target.createTask(mEntity);
}else {
Log.w(TAG, "添加命令执行失败,【该任务已经存在】");
}
} }
} }

View File

@ -2,6 +2,7 @@ package com.arialyy.downloadutil.core.command;
import android.content.Context; import android.content.Context;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -15,6 +16,12 @@ class CancelCommand extends IDownloadCommand {
} }
@Override public void executeComment() { @Override public void executeComment() {
target.cancelTask(target.getTask(mEntity)); Task task = target.getTask(mEntity);
if (task == null){
task = target.createTask(mEntity);
}
if (task != null) {
target.cancelTask(task);
}
} }
} }

View File

@ -6,6 +6,7 @@ import com.arialyy.downloadutil.core.DownloadTarget;
import com.arialyy.downloadutil.core.IDownloadTarget; import com.arialyy.downloadutil.core.IDownloadTarget;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.help.CheckHelp; import com.arialyy.downloadutil.help.CheckHelp;
import com.arialyy.downloadutil.util.Util;
/** /**
* Created by lyy on 2016/8/22. * Created by lyy on 2016/8/22.
@ -15,6 +16,7 @@ public abstract class IDownloadCommand {
protected IDownloadTarget target; protected IDownloadTarget target;
protected Context mContext; protected Context mContext;
protected DownloadEntity mEntity; protected DownloadEntity mEntity;
protected String TAG;
/** /**
* @param context context * @param context context
@ -27,6 +29,7 @@ public abstract class IDownloadCommand {
target = DownloadTarget.getInstance(); target = DownloadTarget.getInstance();
mContext = context; mContext = context;
mEntity = entity; mEntity = entity;
TAG = Util.getClassName(this);
} }
public Context getContext() { public Context getContext() {

View File

@ -2,6 +2,7 @@ package com.arialyy.downloadutil.core.command;
import android.content.Context; import android.content.Context;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -15,6 +16,12 @@ class StartCommand extends IDownloadCommand {
} }
@Override public void executeComment() { @Override public void executeComment() {
target.startTask(target.getTask(mEntity)); Task task = target.getTask(mEntity);
if (task == null) {
task = target.createTask(mEntity);
}
if (task != null) {
target.startTask(task);
}
} }
} }

View File

@ -19,6 +19,7 @@ class StateCommand extends IDownloadCommand {
} }
@Override public void executeComment() { @Override public void executeComment() {
target.getTaskState(mEntity); target.getTaskState(mEntity);
} }
} }

View File

@ -1,7 +1,9 @@
package com.arialyy.downloadutil.core.command; package com.arialyy.downloadutil.core.command;
import android.content.Context; import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -19,6 +21,11 @@ class StopCommand extends IDownloadCommand {
} }
@Override public void executeComment() { @Override public void executeComment() {
target.stopTask(target.getTask(mEntity)); Task task = target.getTask(mEntity);
if (task != null) {
target.stopTask(task);
} else {
Log.w(TAG, "停止命令执行失败,【调度器中没有该任务】");
}
} }
} }

View File

@ -1,6 +1,6 @@
package com.arialyy.downloadutil.core.inf; package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.util.Task;
/** /**
* Created by lyy on 2016/8/16. * Created by lyy on 2016/8/16.

View File

@ -1,6 +1,6 @@
package com.arialyy.downloadutil.core.inf; package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.util.Task;
/** /**
* Created by lyy on 2016/8/14. * Created by lyy on 2016/8/14.

View File

@ -1,6 +1,6 @@
package com.arialyy.downloadutil.core.inf; package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**

View File

@ -3,7 +3,7 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.inf.IPool; import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
@ -45,14 +45,11 @@ public class CachePool implements IPool {
} }
String url = task.getDownloadEntity().getDownloadUrl(); String url = task.getDownloadEntity().getDownloadUrl();
if (mCacheQueue.contains(task)) { if (mCacheQueue.contains(task)) {
Log.e(TAG, "队列中已经包含了该任务,任务下载链接【" + url + ""); Log.w(TAG, "队列中已经包含了该任务,任务下载链接【" + url + "");
return false; return false;
} else { } else {
boolean s = mCacheQueue.offer(task); boolean s = mCacheQueue.offer(task);
Log.w(TAG, "任务添加" + (s ? Log.d(TAG, "任务添加" + (s ? "成功" : "失败,【" + url + ""));
"成功" :
"失败,【" + url + ""
));
if (s) { if (s) {
mCacheArray.put(Util.keyToHashKey(url), task); mCacheArray.put(Util.keyToHashKey(url), task);
} }

View File

@ -3,7 +3,7 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.inf.IPool; import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
@ -70,10 +70,7 @@ public class ExecutePool implements IPool {
private boolean putNewTask(Task newTask) { private boolean putNewTask(Task newTask) {
String url = newTask.getDownloadEntity().getDownloadUrl(); String url = newTask.getDownloadEntity().getDownloadUrl();
boolean s = mExecuteQueue.offer(newTask); boolean s = mExecuteQueue.offer(newTask);
Log.w(TAG, "任务添加" + (s ? Log.w(TAG, "任务添加" + (s ? "成功" : "失败,【" + url + ""));
"成功" :
"失败,【" + url + ""
));
if (s) { if (s) {
newTask.start(); newTask.start();
mExecuteArray.put(Util.keyToHashKey(url), newTask); mExecuteArray.put(Util.keyToHashKey(url), newTask);

View File

@ -38,14 +38,14 @@ public class DbEntity {
* 删除当前数据 * 删除当前数据
*/ */
public void deleteData() { public void deleteData() {
mUtil.delData(this, new Object[]{"rowid"}, new Object[]{rowID}); mUtil.delData(getClass(), new Object[]{"rowid"}, new Object[]{rowID});
} }
/** /**
* 根据条件删除数据 * 根据条件删除数据
*/ */
public void deleteData(@NonNull Object[] wheres, @NonNull Object[] values) { public void deleteData(@NonNull Object[] wheres, @NonNull Object[] values) {
mUtil.delData(this, wheres, values); mUtil.delData(getClass(), wheres, values);
} }
/** /**
@ -104,8 +104,9 @@ public class DbEntity {
* *
* @return 没有数据返回null * @return 没有数据返回null
*/ */
public <T extends DbEntity> List<T> findAllData(Class<T> clazz) { public static <T extends DbEntity> List<T> findAllData(Class<T> clazz) {
return mUtil.findAllData(clazz, this); DbUtil util = DbUtil.getInstance();
return util.findAllData(clazz);
} }
/** /**
@ -113,9 +114,10 @@ public class DbEntity {
* *
* @return 没有数据返回null * @return 没有数据返回null
*/ */
public <T extends DbEntity> List<T> findDatas(Class<T> clazz, @NonNull String[] wheres, public static <T extends DbEntity> List<T> findDatas(Class<T> clazz, @NonNull String[] wheres,
@NonNull String[] values) { @NonNull String[] values) {
return mUtil.findData(clazz, this, wheres, values); DbUtil util = DbUtil.getInstance();
return util.findData(clazz, wheres, values);
} }
/** /**
@ -123,9 +125,10 @@ public class DbEntity {
* *
* @return 没有数据返回null * @return 没有数据返回null
*/ */
public <T extends DbEntity> T findData(Class<T> clazz, @NonNull String[] wheres, public static <T extends DbEntity> T findData(Class<T> clazz, @NonNull String[] wheres,
@NonNull String[] values) { @NonNull String[] values) {
List<T> datas = mUtil.findData(clazz, this, wheres, values); DbUtil util = DbUtil.getInstance();
List<T> datas = util.findData(clazz, wheres, values);
return datas == null ? null : datas.size() > 0 ? datas.get(0) : null; return datas == null ? null : datas.size() > 0 ? datas.get(0) : null;
} }
} }

View File

@ -62,7 +62,7 @@ public class DbUtil {
/** /**
* 删除某条数据 * 删除某条数据
*/ */
protected void delData(DbEntity dbEntity, @NonNull Object[] wheres, @NonNull Object[] values) { protected void delData(Class clazz, @NonNull Object[] wheres, @NonNull Object[] values) {
mDb = mHelper.getWritableDatabase(); mDb = mHelper.getWritableDatabase();
if (wheres.length <= 0 || values.length <= 0) { if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "输入删除条件"); Log.e(TAG, "输入删除条件");
@ -72,7 +72,7 @@ public class DbUtil {
return; return;
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("DELETE FROM ").append(Util.getClassName(dbEntity)).append(" WHERE "); sb.append("DELETE FROM ").append(Util.getClassName(clazz)).append(" WHERE ");
int i = 0; int i = 0;
for (Object where : wheres) { for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'"); sb.append(where).append("=").append("'").append(values[i]).append("'");
@ -121,10 +121,10 @@ public class DbUtil {
/** /**
* 遍历所有数据 * 遍历所有数据
*/ */
protected <T extends DbEntity> List<T> findAllData(Class<T> clazz, DbEntity dbEntity) { protected <T extends DbEntity> List<T> findAllData(Class<T> clazz) {
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(dbEntity)); sb.append("SELECT rowid, * FROM ").append(Util.getClassName(clazz));
print(FIND_ALL_DATA, sb.toString()); print(FIND_ALL_DATA, sb.toString());
Cursor cursor = mDb.rawQuery(sb.toString(), null); Cursor cursor = mDb.rawQuery(sb.toString(), null);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
@ -133,8 +133,7 @@ public class DbUtil {
/** /**
* 条件查寻数据 * 条件查寻数据
*/ */
protected <T extends DbEntity> List<T> findData(Class<T> clazz, DbEntity dbEntity, protected <T extends DbEntity> List<T> findData(Class<T> clazz, @NonNull String[] wheres,
@NonNull String[] wheres,
@NonNull String[] values) { @NonNull String[] values) {
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
if (wheres.length <= 0 || values.length <= 0) { if (wheres.length <= 0 || values.length <= 0) {
@ -145,7 +144,7 @@ public class DbUtil {
return null; return null;
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(Util.getClassName(dbEntity)).append(" where "); sb.append("SELECT rowid, * FROM ").append(Util.getClassName(clazz)).append(" where ");
int i = 0; int i = 0;
for (Object where : wheres) { for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'"); sb.append(where).append("=").append("'").append(values[i]).append("'");
@ -161,10 +160,10 @@ public class DbUtil {
* 插入数据 * 插入数据
*/ */
protected void insertData(DbEntity dbEntity) { protected void insertData(DbEntity dbEntity) {
mDb = mHelper.getWritableDatabase();
if (!tableExists(dbEntity)) { if (!tableExists(dbEntity)) {
createTable(dbEntity); createTable(dbEntity);
} }
mDb = mHelper.getWritableDatabase();
Class<?> clazz = dbEntity.getClass(); Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz); Field[] fields = Util.getFields(clazz);
if (fields != null && fields.length > 0) { if (fields != null && fields.length > 0) {
@ -209,6 +208,9 @@ public class DbUtil {
* 查找某张表是否存在 * 查找某张表是否存在
*/ */
public synchronized boolean tableExists(DbEntity dbEntity) { public synchronized boolean tableExists(DbEntity dbEntity) {
if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getReadableDatabase();
}
Cursor cursor = null; Cursor cursor = null;
try { try {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -227,6 +229,7 @@ public class DbUtil {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (cursor != null) cursor.close(); if (cursor != null) cursor.close();
close();
} }
return false; return false;
} }
@ -235,6 +238,9 @@ public class DbUtil {
* 创建表 * 创建表
*/ */
private void createTable(DbEntity dbEntity) { private void createTable(DbEntity dbEntity) {
if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getWritableDatabase();
}
Field[] fields = Util.getFields(dbEntity.getClass()); Field[] fields = Util.getFields(dbEntity.getClass());
if (fields != null && fields.length > 0) { if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -271,6 +277,7 @@ public class DbUtil {
print(CREATE_TABLE, str); print(CREATE_TABLE, str);
mDb.execSQL(str); mDb.execSQL(str);
} }
close();
} }
/** /**

View File

@ -5,6 +5,8 @@ import android.support.annotation.NonNull;
import android.util.Log; import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import com.arialyy.downloadutil.entity.DownloadEntity;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -18,7 +20,7 @@ import java.util.Properties;
* Created by lyy on 2015/8/25. * Created by lyy on 2015/8/25.
* 下载工具类 * 下载工具类
*/ */
public class DownLoadUtil { final class DownLoadUtil {
private static final String TAG = "DownLoadUtil"; private static final String TAG = "DownLoadUtil";
//下载监听 //下载监听
private IDownloadListener mListener; private IDownloadListener mListener;
@ -38,8 +40,13 @@ public class DownLoadUtil {
boolean isNewTask = true; boolean isNewTask = true;
private int mCancelNum = 0; private int mCancelNum = 0;
private int mStopNum = 0; private int mStopNum = 0;
private Context mContext;
private DownloadEntity mDownloadEntity;
public DownLoadUtil() {
public DownLoadUtil(Context context, DownloadEntity entity) {
mContext = context.getApplicationContext();
mDownloadEntity = entity;
} }
public IDownloadListener getListener() { public IDownloadListener getListener() {
@ -71,27 +78,50 @@ public class DownLoadUtil {
isStop = true; isStop = true;
} }
/**
* 删除下载记录文件
*/
public void delConfigFile() {
if (mContext != null && mDownloadEntity != null) {
File dFile = new File(mDownloadEntity.getDownloadPath());
File config = new File(
mContext.getFilesDir().getPath() + "/temp/" + dFile.getName() + ".properties");
if (config.exists()) {
config.delete();
}
}
}
/**
* 删除temp文件
*/
public void delTempFile() {
if (mContext != null && mDownloadEntity != null) {
File dFile = new File(mDownloadEntity.getDownloadPath());
if (dFile.exists()) {
dFile.delete();
}
}
}
/** /**
* 多线程断点续传下载文件,暂停和继续 * 多线程断点续传下载文件,暂停和继续
* *
* @param context 必须添加该参数不能使用全局变量的context
* @param downloadUrl 下载路径
* @param filePath 保存路径
* @param downloadListener 下载进度监听 {@link DownloadListener} * @param downloadListener 下载进度监听 {@link DownloadListener}
*/ */
public void download(final Context context, @NonNull final String downloadUrl, public void start(@NonNull final IDownloadListener downloadListener) {
@NonNull final String filePath,
@NonNull final IDownloadListener downloadListener) {
isDownloading = true; isDownloading = true;
mCurrentLocation = 0; mCurrentLocation = 0;
isStop = false; isStop = false;
isCancel = false; isCancel = false;
mCancelNum = 0; mCancelNum = 0;
mStopNum = 0; mStopNum = 0;
final String filePath = mDownloadEntity.getDownloadPath();
final String downloadUrl = mDownloadEntity.getDownloadUrl();
final File dFile = new File(filePath); final File dFile = new File(filePath);
//读取已完成的线程数 //读取已完成的线程数
final File configFile = new File( final File configFile = new File(
context.getFilesDir().getPath() + "/temp/" + dFile.getName() + ".properties"); mContext.getFilesDir().getPath() + "/temp/" + dFile.getName() + ".properties");
try { try {
if (!configFile.exists()) { //记录文件被删除,则重新下载 if (!configFile.exists()) { //记录文件被删除,则重新下载
isNewTask = true; isNewTask = true;
@ -149,8 +179,8 @@ public class DownLoadUtil {
} }
} }
} }
int blockSize = fileLength / THREAD_NUM;
SparseArray<Thread> tasks = new SparseArray<>(); SparseArray<Thread> tasks = new SparseArray<>();
int blockSize = fileLength / THREAD_NUM;
int[] recordL = new int[THREAD_NUM]; int[] recordL = new int[THREAD_NUM];
int rl = 0; int rl = 0;
for (int i = 0; i < THREAD_NUM; i++) { for (int i = 0; i < THREAD_NUM; i++) {
@ -194,11 +224,12 @@ public class DownLoadUtil {
rl++; rl++;
} }
if (i == (THREAD_NUM - 1)) { if (i == (THREAD_NUM - 1)) {
endL = fileLength;//如果整个文件的大小不为线程个数的整数倍,则最后一个线程的结束位置即为文件的总长度 //如果整个文件的大小不为线程个数的整数倍,则最后一个线程的结束位置即为文件的总长度
endL = fileLength;
} }
DownloadEntity entity = new DownloadEntity(context, fileLength, ConfigEntity entity = new ConfigEntity(mContext, fileLength,
downloadUrl, dFile, i, downloadUrl, dFile, i, startL,
startL, endL); endL);
DownLoadTask task = new DownLoadTask(entity); DownLoadTask task = new DownLoadTask(entity);
tasks.put(i, new Thread(task)); tasks.put(i, new Thread(task));
} }
@ -238,10 +269,10 @@ public class DownLoadUtil {
*/ */
private class DownLoadTask implements Runnable { private class DownLoadTask implements Runnable {
private static final String TAG = "DownLoadTask"; private static final String TAG = "DownLoadTask";
private DownloadEntity dEntity; private ConfigEntity dEntity;
private String configFPath; private String configFPath;
public DownLoadTask(DownloadEntity downloadInfo) { public DownLoadTask(ConfigEntity downloadInfo) {
this.dEntity = downloadInfo; this.dEntity = downloadInfo;
configFPath = dEntity.context.getFilesDir() configFPath = dEntity.context.getFilesDir()
.getPath() + "/temp/" + dEntity.tempFile.getName() + ".properties"; .getPath() + "/temp/" + dEntity.tempFile.getName() + ".properties";
@ -392,7 +423,7 @@ public class DownLoadUtil {
/** /**
* 子线程下载信息类 * 子线程下载信息类
*/ */
private class DownloadEntity { private class ConfigEntity {
//文件大小 //文件大小
long fileSize; long fileSize;
String downloadUrl; String downloadUrl;
@ -402,7 +433,7 @@ public class DownLoadUtil {
File tempFile; File tempFile;
Context context; Context context;
public DownloadEntity(Context context, long fileSize, String downloadUrl, File file, public ConfigEntity(Context context, long fileSize, String downloadUrl, File file,
int threadId, long startLocation, long endLocation) { int threadId, long startLocation, long endLocation) {
this.fileSize = fileSize; this.fileSize = fileSize;
this.downloadUrl = downloadUrl; this.downloadUrl = downloadUrl;

View File

@ -7,7 +7,7 @@
//import android.database.sqlite.SQLiteOpenHelper; //import android.database.sqlite.SQLiteOpenHelper;
//import android.support.annotation.NonNull; //import android.support.annotation.NonNull;
// //
//import com.arialyy.downloadutil.entity.DownloadEntity; //import com.arialyy.downloadutil.entity.ConfigEntity;
// //
//import java.util.ArrayList; //import java.util.ArrayList;
//import java.util.List; //import java.util.List;
@ -50,8 +50,8 @@
// /** // /**
// * 获取所有下载实体 // * 获取所有下载实体
// */ // */
// public List<DownloadEntity> getAllEntity(@NonNull SQLiteDatabase db) { // public List<ConfigEntity> getAllEntity(@NonNull SQLiteDatabase db) {
// List<DownloadEntity> list = new ArrayList<>(); // List<ConfigEntity> list = new ArrayList<>();
// Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null); // Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null);
// if (c.moveToFirst()) { // if (c.moveToFirst()) {
// while (c.moveToNext()) { // while (c.moveToNext()) {
@ -65,7 +65,7 @@
// /** // /**
// * 更新下载实体 // * 更新下载实体
// */ // */
// public void updateEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) { // public void updateEntity(@NonNull SQLiteDatabase db, ConfigEntity entity) {
// String whereClause = "url=?"; // String whereClause = "url=?";
// String[] whereArgs = {entity.getDownloadUrl()}; // String[] whereArgs = {entity.getDownloadUrl()};
// db.update(TABLE_NAME, createCv(entity), whereClause, whereArgs); // db.update(TABLE_NAME, createCv(entity), whereClause, whereArgs);
@ -74,7 +74,7 @@
// /** // /**
// * 删除下载实体 // * 删除下载实体
// */ // */
// public void delEntity(@NonNull SQLiteDatabase db, DownloadEntity entity) { // public void delEntity(@NonNull SQLiteDatabase db, ConfigEntity entity) {
// delEntity(db, entity.getDownloadUrl()); // delEntity(db, entity.getDownloadUrl());
// } // }
// //
@ -93,8 +93,8 @@
// * @param downloadUrl // * @param downloadUrl
// * @return // * @return
// */ // */
// public DownloadEntity findEntity(@NonNull SQLiteDatabase db, @NonNull String downloadUrl) { // public ConfigEntity findEntity(@NonNull SQLiteDatabase db, @NonNull String downloadUrl) {
// DownloadEntity entity; // ConfigEntity entity;
// String sql = "select * from " + TABLE_NAME + "where url=?"; // String sql = "select * from " + TABLE_NAME + "where url=?";
// Cursor c = db.rawQuery(sql, new String[]{downloadUrl}); // Cursor c = db.rawQuery(sql, new String[]{downloadUrl});
// if (c.getCount() <= 0) { // if (c.getCount() <= 0) {
@ -113,8 +113,8 @@
// * // *
// * @param entity // * @param entity
// */ // */
// public void savaEntity(@NonNull SQLiteDatabase db, @NonNull DownloadEntity entity) { // public void savaEntity(@NonNull SQLiteDatabase db, @NonNull ConfigEntity entity) {
// DownloadEntity temp = findEntity(db, entity.getDownloadUrl()); // ConfigEntity temp = findEntity(db, entity.getDownloadUrl());
// if (temp == null) { // if (temp == null) {
// db.insert(TABLE_NAME, null, createCv(entity)); // db.insert(TABLE_NAME, null, createCv(entity));
// } else { // } else {
@ -128,9 +128,9 @@
// * @param c // * @param c
// * @return // * @return
// */ // */
// private DownloadEntity cursor2Entity(Cursor c) { // private ConfigEntity cursor2Entity(Cursor c) {
// DownloadEntity entity; // ConfigEntity entity;
// entity = new DownloadEntity(); // entity = new ConfigEntity();
// entity.setDownloadUrl(c.getString(c.getColumnIndex("url"))); // entity.setDownloadUrl(c.getString(c.getColumnIndex("url")));
// entity.setDownloadPath(c.getString(c.getColumnIndex("path"))); // entity.setDownloadPath(c.getString(c.getColumnIndex("path")));
// entity.setCompleteTime(c.getLong(c.getColumnIndex("completeTime"))); // entity.setCompleteTime(c.getLong(c.getColumnIndex("completeTime")));
@ -148,7 +148,7 @@
// * @param entity // * @param entity
// * @return // * @return
// */ // */
// private ContentValues createCv(@NonNull DownloadEntity entity) { // private ContentValues createCv(@NonNull ConfigEntity entity) {
// ContentValues cv = new ContentValues(); // ContentValues cv = new ContentValues();
// cv.put("url", entity.getDownloadUrl()); // cv.put("url", entity.getDownloadUrl());
// cv.put("path", entity.getDownloadPath()); // cv.put("path", entity.getDownloadPath());

View File

@ -1,4 +1,4 @@
package com.arialyy.downloadutil.core; package com.arialyy.downloadutil.util;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -6,9 +6,9 @@ import android.net.Uri;
import android.os.Handler; import android.os.Handler;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.core.IDownloadTarget;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.DownLoadUtil;
import com.arialyy.downloadutil.util.IDownloadListener;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -19,41 +19,42 @@ import java.net.HttpURLConnection;
public class Task { public class Task {
public static final String TAG = "Task"; public static final String TAG = "Task";
private DownloadEntity downloadEntity; private DownloadEntity mEntity;
private IDownloadListener listener; private IDownloadListener mListener;
private Handler outHandler; private Handler mOutHandler;
private Context context; private Context mContext;
private DownLoadUtil util; private DownLoadUtil mUtil;
private Task() { private Task(Context context, DownloadEntity entity) {
util = new DownLoadUtil(); mContext = context.getApplicationContext();
mEntity = entity;
mUtil = new DownLoadUtil(context, entity);
} }
/** /**
* 开始下载 * 开始下载
*/ */
public void start() { public void start() {
if (util.isDownloading()) { if (mUtil.isDownloading()) {
Log.d(TAG, "任务正在下载"); Log.d(TAG, "任务正在下载");
} else { } else {
if (listener == null) { if (mListener == null) {
listener = new DownloadListener(context, downloadEntity, outHandler); mListener = new DownloadListener(mContext, mEntity, mOutHandler);
} }
util.download(context, downloadEntity.getDownloadUrl(), mUtil.start(mListener);
downloadEntity.getDownloadPath(), listener);
} }
} }
public DownloadEntity getDownloadEntity() { public DownloadEntity getDownloadEntity() {
return downloadEntity; return mEntity;
} }
/** /**
* 停止下载 * 停止下载
*/ */
public void stop() { public void stop() {
if (util.isDownloading()) { if (mUtil.isDownloading()) {
util.stopDownload(); mUtil.stopDownload();
} }
} }
@ -61,14 +62,38 @@ public class Task {
* 获取下载工具 * 获取下载工具
*/ */
public DownLoadUtil getDownloadUtil() { public DownLoadUtil getDownloadUtil() {
return util; return mUtil;
}
/**
* 任务下载状态
*/
public boolean isDownloading() {
return mUtil.isDownloading();
} }
/** /**
* 取消下载 * 取消下载
*/ */
public void cancel() { public void cancel() {
util.cancelDownload(); if (mUtil.isDownloading()) {
mUtil.cancelDownload();
} else {
// 如果任务不是下载状态
mUtil.cancelDownload();
mUtil.delConfigFile();
mUtil.delTempFile();
mEntity.deleteData();
//发送取消下载的广播
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);
mContext.sendBroadcast(intent);
}
} }
/** /**
@ -167,7 +192,8 @@ public class Task {
} }
private void sendIntent(String action, long location) { private void sendIntent(String action, long location) {
downloadEntity.save(); downloadEntity.setCurrentProgress(location);
downloadEntity.update();
Uri.Builder builder = new Uri.Builder(); Uri.Builder builder = new Uri.Builder();
builder.scheme(context.getPackageName()); builder.scheme(context.getPackageName());
Uri uri = builder.build(); Uri uri = builder.build();
@ -202,12 +228,11 @@ public class Task {
return this; return this;
} }
public Task builder() { public Task build() {
Task task = new Task(); Task task = new Task(context, downloadEntity);
task.context = context; task.mListener = listener;
task.downloadEntity = downloadEntity; task.mOutHandler = outHandler;
task.listener = listener; downloadEntity.save();
task.outHandler = outHandler;
return task; return task;
} }
} }

View File

@ -103,6 +103,17 @@ public class Util {
return arrays[arrays.length - 1]; return arrays[arrays.length - 1];
} }
/**
* 获取对象名
*
* @param clazz clazz
* @return 对象名
*/
public static String getClassName(Class clazz) {
String arrays[] = clazz.getName().split("\\.");
return arrays[arrays.length - 1];
}
/** /**
* 格式化文件大小 * 格式化文件大小
* *