Merge branch 'v_3.0' of https://github.com/AriaLyy/Aria into v_3.0

pull/330/head
AriaLyy 8 years ago
commit 31dfc5a234
  1. 65
      Aria/src/main/java/com/arialyy/aria/core/Aria.java
  2. 38
      Aria/src/main/java/com/arialyy/aria/core/AriaManager.java
  3. 15
      Aria/src/main/java/com/arialyy/aria/core/command/AbsCmd.java
  4. 11
      Aria/src/main/java/com/arialyy/aria/core/command/AddCmd.java
  5. 14
      Aria/src/main/java/com/arialyy/aria/core/command/CancelCmd.java
  6. 2
      Aria/src/main/java/com/arialyy/aria/core/command/CmdFactory.java
  7. 12
      Aria/src/main/java/com/arialyy/aria/core/command/StartCmd.java
  8. 21
      Aria/src/main/java/com/arialyy/aria/core/command/StopCmd.java
  9. 1
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadEntity.java
  10. 38
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadReceiver.java
  11. 121
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTarget.java
  12. 11
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTask.java
  13. 12
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTaskEntity.java
  14. 65
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTaskFactory.java
  15. 175
      Aria/src/main/java/com/arialyy/aria/core/inf/AbsTarget.java
  16. 17
      Aria/src/main/java/com/arialyy/aria/core/inf/IEntity.java
  17. 26
      Aria/src/main/java/com/arialyy/aria/core/inf/IReceiver.java
  18. 17
      Aria/src/main/java/com/arialyy/aria/core/inf/ITask.java
  19. 31
      Aria/src/main/java/com/arialyy/aria/core/inf/ITaskEntity.java
  20. 21
      Aria/src/main/java/com/arialyy/aria/core/queue/AbsTaskQueue.java
  21. 13
      Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java
  22. 27
      Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java
  23. 92
      Aria/src/main/java/com/arialyy/aria/core/queue/TaskFactory.java
  24. 120
      Aria/src/main/java/com/arialyy/aria/core/queue/UploadTaskQueue.java
  25. 11
      Aria/src/main/java/com/arialyy/aria/core/queue/pool/CachePool.java
  26. 11
      Aria/src/main/java/com/arialyy/aria/core/queue/pool/ExecutePool.java
  27. 2
      Aria/src/main/java/com/arialyy/aria/core/queue/pool/IPool.java
  28. 74
      Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java
  29. 54
      Aria/src/main/java/com/arialyy/aria/core/scheduler/ISchedulers.java
  30. 20
      Aria/src/main/java/com/arialyy/aria/core/scheduler/OnSchedulerListener.java
  31. 185
      Aria/src/main/java/com/arialyy/aria/core/scheduler/UploadSchedulers.java
  32. 97
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadEntity.java
  33. 95
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadReceiver.java
  34. 115
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTarget.java
  35. 170
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTask.java
  36. 31
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTaskEntity.java
  37. 49
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTaskQueue.java
  38. 40
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadUtil.java
  39. 7
      Aria/src/main/java/com/arialyy/aria/util/CheckUtil.java
  40. 5
      Aria/src/main/java/com/arialyy/aria/util/CommonUtil.java
  41. 2
      app/src/main/java/com/arialyy/simple/dialog_task/DownloadDialog.java
  42. 2
      app/src/main/java/com/arialyy/simple/fragment_task/DownloadFragment.java
  43. 4
      app/src/main/java/com/arialyy/simple/multi_task/DownloadActivity.java
  44. 2
      app/src/main/java/com/arialyy/simple/multi_task/MultiTaskActivity.java
  45. 2
      app/src/main/java/com/arialyy/simple/notification/SimpleNotification.java
  46. 2
      app/src/main/java/com/arialyy/simple/pop_task/DownloadPopupWindow.java
  47. 2
      app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java
  48. 18
      app/src/main/res/layout/activity_upload.xml

@ -29,6 +29,8 @@ import android.widget.PopupWindow;
import com.arialyy.aria.core.download.DownloadReceiver; import com.arialyy.aria.core.download.DownloadReceiver;
import com.arialyy.aria.core.scheduler.OnSchedulerListener; import com.arialyy.aria.core.scheduler.OnSchedulerListener;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.upload.UploadReceiver;
import com.arialyy.aria.core.upload.UploadTask;
/** /**
* Created by lyy on 2016/12/1. * Created by lyy on 2016/12/1.
@ -36,7 +38,7 @@ import com.arialyy.aria.core.download.DownloadTask;
* Aria启动管理全局任务 * Aria启动管理全局任务
* <pre> * <pre>
* <code> * <code>
* //启动下载 * //下载
* Aria.download(this) * Aria.download(this)
* .load(DOWNLOAD_URL) //下载地址,必填 * .load(DOWNLOAD_URL) //下载地址,必填
* //文件保存路径,必填 * //文件保存路径,必填
@ -44,6 +46,15 @@ import com.arialyy.aria.core.download.DownloadTask;
* .setDownloadName("test.apk") //文件名,必填 * .setDownloadName("test.apk") //文件名,必填
* .start(); * .start();
* </code> * </code>
* <code>
* //上传
* Aria.upload(this)
* .load(filePath) //文件路径,必填
* .setUploadUrl(uploadUrl) //上传路径,必填
* .setFileName(fileName) //文件名
* .setAttachment(fileKey) //服务器读取文件的key
* .start();
* </code>
* </pre> * </pre>
*/ */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) public class Aria { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) public class Aria {
@ -108,6 +119,15 @@ import com.arialyy.aria.core.download.DownloadTask;
return get(obj).download(obj); return get(obj).download(obj);
} }
/**
* 初始化上传
*
* @param obj 支持类型有ActivityServiceApplicationDialogFragmentFragmentPopupWindowDialog
*/
public static UploadReceiver upload(Object obj) {
return get(obj).upload(obj);
}
/** /**
* 处理通用事件 * 处理通用事件
* *
@ -142,7 +162,48 @@ import com.arialyy.aria.core.download.DownloadTask;
} }
} }
public static class SimpleSchedulerListener implements OnSchedulerListener { /**
* 上传任务状态监听
*/
public static class UploadSchedulerListener implements OnSchedulerListener<UploadTask> {
@Override public void onTaskPre(UploadTask task) {
}
@Override public void onTaskResume(UploadTask task) {
}
@Override public void onTaskStart(UploadTask task) {
}
@Override public void onTaskStop(UploadTask task) {
}
@Override public void onTaskCancel(UploadTask task) {
}
@Override public void onTaskFail(UploadTask task) {
}
@Override public void onTaskComplete(UploadTask task) {
}
@Override public void onTaskRunning(UploadTask task) {
}
}
/**
* 下载任务状态监听
*/
public static class DownloadSchedulerListener implements OnSchedulerListener<DownloadTask> {
@Override public void onTaskPre(DownloadTask task) { @Override public void onTaskPre(DownloadTask task) {

@ -33,7 +33,7 @@ import com.arialyy.aria.core.download.DownloadReceiver;
import com.arialyy.aria.core.inf.ICmd; import com.arialyy.aria.core.inf.ICmd;
import com.arialyy.aria.core.inf.IReceiver; import com.arialyy.aria.core.inf.IReceiver;
import com.arialyy.aria.core.queue.DownloadTaskQueue; import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.queue.ITaskQueue; import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadReceiver; import com.arialyy.aria.core.upload.UploadReceiver;
import com.arialyy.aria.orm.DbEntity; import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.orm.DbUtil; import com.arialyy.aria.orm.DbUtil;
@ -56,16 +56,13 @@ import java.util.Map;
private static final String UPLOAD = "_upload"; private static final String UPLOAD = "_upload";
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
@SuppressLint("StaticFieldLeak") private static volatile AriaManager INSTANCE = null; @SuppressLint("StaticFieldLeak") private static volatile AriaManager INSTANCE = null;
Map<String, IReceiver> mReceivers = new HashMap<>(); private Map<String, IReceiver> mReceivers = new HashMap<>();
private LifeCallback mLifeCallback;
DownloadTaskQueue mDTaskQueue;
public static Context APP; public static Context APP;
private List<ICmd> mCommands = new ArrayList<>(); private List<ICmd> mCommands = new ArrayList<>();
private AriaManager(Context context) { private AriaManager(Context context) {
DbUtil.init(context.getApplicationContext()); DbUtil.init(context.getApplicationContext());
APP = context; APP = context.getApplicationContext();
regAppLifeCallback(context); regAppLifeCallback(context);
} }
@ -82,17 +79,6 @@ import java.util.Map;
return mReceivers; return mReceivers;
} }
public List<DownloadEntity> getAllDownloadEntity() {
return DbEntity.findAllData(DownloadEntity.class);
}
/**
* 获取任务队列
*/
public DownloadTaskQueue getTaskQueue() {
return mDTaskQueue;
}
/** /**
* 设置命令 * 设置命令
*/ */
@ -132,6 +118,17 @@ import java.util.Map;
return (receiver instanceof DownloadReceiver) ? (DownloadReceiver) receiver : null; return (receiver instanceof DownloadReceiver) ? (DownloadReceiver) receiver : null;
} }
/**
* 处理上传操作
*/
UploadReceiver upload(Object obj) {
IReceiver receiver = mReceivers.get(getKey(false, obj));
if (receiver == null) {
receiver = putReceiver(true, obj);
}
return (receiver instanceof UploadReceiver) ? (UploadReceiver) receiver : null;
}
/** /**
* 设置CA证书信息 * 设置CA证书信息
* *
@ -192,7 +189,7 @@ import java.util.Map;
Log.w(TAG, "最大任务数不能小于 1"); Log.w(TAG, "最大任务数不能小于 1");
return this; return this;
} }
mDTaskQueue.setDownloadNum(maxDownloadNum); DownloadTaskQueue.getInstance().setDownloadNum(maxDownloadNum);
return this; return this;
} }
@ -214,7 +211,8 @@ import java.util.Map;
receiver = dReceiver; receiver = dReceiver;
} else { } else {
UploadReceiver uReceiver = new UploadReceiver(); UploadReceiver uReceiver = new UploadReceiver();
uReceiver.targetName = obj.getClass().getName();
mReceivers.put(key, uReceiver);
receiver = uReceiver; receiver = uReceiver;
} }
} }
@ -267,7 +265,7 @@ import java.util.Map;
private void regAppLifeCallback(Context context) { private void regAppLifeCallback(Context context) {
Context app = context.getApplicationContext(); Context app = context.getApplicationContext();
if (app instanceof Application) { if (app instanceof Application) {
mLifeCallback = new LifeCallback(); LifeCallback mLifeCallback = new LifeCallback();
((Application) app).registerActivityLifecycleCallbacks(mLifeCallback); ((Application) app).registerActivityLifecycleCallbacks(mLifeCallback);
} }
} }

@ -16,10 +16,13 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import com.arialyy.aria.core.AriaManager; import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.queue.ITaskQueue; import com.arialyy.aria.core.queue.ITaskQueue;
import com.arialyy.aria.core.inf.ICmd; import com.arialyy.aria.core.inf.ICmd;
import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadTaskEntity;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
@ -27,7 +30,7 @@ import com.arialyy.aria.util.CommonUtil;
* Created by lyy on 2016/8/22. * Created by lyy on 2016/8/22.
* 下载命令 * 下载命令
*/ */
public abstract class IDownloadCmd<T extends ITaskEntity> implements ICmd { public abstract class AbsCmd<T extends ITaskEntity> implements ICmd {
ITaskQueue mQueue; ITaskQueue mQueue;
T mEntity; T mEntity;
String TAG; String TAG;
@ -36,11 +39,15 @@ public abstract class IDownloadCmd<T extends ITaskEntity> implements ICmd {
/** /**
* @param targetName 产生任务的对象名 * @param targetName 产生任务的对象名
*/ */
IDownloadCmd(String targetName, T entity) { AbsCmd(String targetName, T entity) {
CheckUtil.checkTaskEntity(entity); CheckUtil.checkTaskEntity(entity);
mTargetName = targetName; mTargetName = targetName;
mEntity = entity; mEntity = entity;
TAG = CommonUtil.getClassName(this); TAG = CommonUtil.getClassName(this);
mQueue = AriaManager.getInstance(AriaManager.APP).getTaskQueue(); if (entity instanceof DownloadTaskEntity) {
mQueue = DownloadTaskQueue.getInstance();
} else if (entity instanceof UploadTaskEntity) {
mQueue = UploadTaskQueue.getInstance();
}
} }
} }

@ -16,20 +16,27 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import android.util.Log;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
/** /**
* Created by lyy on 2016/8/22. * Created by lyy on 2016/8/22.
* 添加任务的命令 * 添加任务的命令
*/ */
class AddCmd<T extends ITaskEntity> extends IDownloadCmd<T> { class AddCmd<T extends ITaskEntity> extends AbsCmd<T> {
AddCmd(String targetName, T entity) { AddCmd(String targetName, T entity) {
super(targetName, entity); super(targetName, entity);
} }
@Override public void executeCmd() { @Override public void executeCmd() {
ITask task = mQueue.getTask(mEntity.getEntity());
if (task == null){
mQueue.createTask(mTargetName, mEntity);
}else {
Log.w(TAG, "添加命令执行失败,【该任务已经存在】");
}
} }
//AddCmd(DownloadTaskEntity entity) { //AddCmd(DownloadTaskEntity entity) {

@ -16,19 +16,29 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
/** /**
* Created by lyy on 2016/9/20. * Created by lyy on 2016/9/20.
* 取消命令 * 取消命令
*/ */
class CancelCmd<T extends ITaskEntity> extends IDownloadCmd<T> { class CancelCmd<T extends ITaskEntity> extends AbsCmd<T> {
CancelCmd(String targetName, T entity) { CancelCmd(String targetName, T entity) {
super(targetName, entity); super(targetName, entity);
} }
@Override public void executeCmd() { @Override public void executeCmd() {
ITask task = mQueue.getTask(mEntity.getEntity());
if (task == null) {
task = mQueue.createTask(mTargetName, mEntity);
}
if (task != null) {
if (mTargetName != null) {
task.setTargetName(mTargetName);
}
mQueue.cancelTask(task);
}
} }
//CancelCmd(DownloadTaskEntity entity) { //CancelCmd(DownloadTaskEntity entity) {

@ -67,7 +67,7 @@ public class CmdFactory {
* @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link * @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link
* #TASK_STOP} * #TASK_STOP}
*/ */
public <T extends ITaskEntity> IDownloadCmd createCmd(String target, T entity, int type) { public <T extends ITaskEntity> AbsCmd createCmd(String target, T entity, int type) {
switch (type) { switch (type) {
case TASK_CREATE: case TASK_CREATE:
return createAddCmd(target, entity); return createAddCmd(target, entity);

@ -16,20 +16,28 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
/** /**
* Created by lyy on 2016/8/22. * Created by lyy on 2016/8/22.
* 开始命令 * 开始命令
*/ */
class StartCmd<T extends ITaskEntity> extends IDownloadCmd<T> { class StartCmd<T extends ITaskEntity> extends AbsCmd<T> {
StartCmd(String targetName, T entity) { StartCmd(String targetName, T entity) {
super(targetName, entity); super(targetName, entity);
} }
@Override public void executeCmd() { @Override public void executeCmd() {
ITask task = mQueue.getTask(mEntity.getEntity());
if (task == null) {
task = mQueue.createTask(mTargetName, mEntity);
}
if (task != null) {
task.setTargetName(mTargetName);
mQueue.startTask(task);
}
} }
//StartCmd(DownloadTaskEntity entity) { //StartCmd(DownloadTaskEntity entity) {

@ -16,20 +16,37 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
/** /**
* Created by lyy on 2016/9/20. * Created by lyy on 2016/9/20.
* 停止命令 * 停止命令
*/ */
class StopCmd<T extends ITaskEntity> extends IDownloadCmd<T> { class StopCmd<T extends ITaskEntity> extends AbsCmd<T> {
StopCmd(String targetName, T entity) { StopCmd(String targetName, T entity) {
super(targetName, entity); super(targetName, entity);
} }
@Override public void executeCmd() { @Override public void executeCmd() {
ITask task = mQueue.getTask(mEntity.getEntity());
if (task == null) {
if (mEntity.getEntity().getState() == IEntity.STATE_RUNNING) {
task = mQueue.createTask(mTargetName, mEntity);
mQueue.stopTask(task);
} else {
Log.w(TAG, "停止命令执行失败,【调度器中没有该任务】");
}
} else {
if (!TextUtils.isEmpty(mTargetName)) {
task.setTargetName(mTargetName);
}
mQueue.stopTask(task);
}
} }
//StopCmd(DownloadTaskEntity entity) { //StopCmd(DownloadTaskEntity entity) {

@ -129,6 +129,7 @@ public class DownloadEntity extends DbEntity implements Parcelable, IEntity{
this.fileSize = fileSize; this.fileSize = fileSize;
} }
@Override
public int getState() { public int getState() {
return state; return state;
} }

@ -19,9 +19,10 @@ import android.support.annotation.NonNull;
import com.arialyy.aria.core.AriaManager; import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.IReceiver; import com.arialyy.aria.core.inf.IReceiver;
import com.arialyy.aria.core.command.CmdFactory; import com.arialyy.aria.core.command.CmdFactory;
import com.arialyy.aria.core.command.IDownloadCmd; import com.arialyy.aria.core.command.AbsCmd;
import com.arialyy.aria.core.scheduler.DownloadSchedulers; import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.OnSchedulerListener; import com.arialyy.aria.core.scheduler.OnSchedulerListener;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,10 +33,10 @@ import java.util.Set;
* Created by lyy on 2016/12/5. * Created by lyy on 2016/12/5.
* 下载功能接收器 * 下载功能接收器
*/ */
public class DownloadReceiver implements IReceiver { public class DownloadReceiver implements IReceiver<DownloadEntity> {
private static final String TAG = "DownloadReceiver"; private static final String TAG = "DownloadReceiver";
public String targetName; public String targetName;
public OnSchedulerListener listener; public OnSchedulerListener<DownloadTask> listener;
/** /**
* {@link #load(String)}请使用该方法 * {@link #load(String)}请使用该方法
@ -61,7 +62,7 @@ public class DownloadReceiver implements IReceiver {
/** /**
* 添加调度器回调 * 添加调度器回调
*/ */
public DownloadReceiver addSchedulerListener(OnSchedulerListener listener) { public DownloadReceiver addSchedulerListener(OnSchedulerListener<DownloadTask> listener) {
this.listener = listener; this.listener = listener;
DownloadSchedulers.getInstance().addSchedulerListener(targetName, listener); DownloadSchedulers.getInstance().addSchedulerListener(targetName, listener);
return this; return this;
@ -81,13 +82,6 @@ public class DownloadReceiver implements IReceiver {
listener = null; listener = null;
} }
/**
* 获取下载列表
*/
public List<DownloadEntity> getDownloadList() {
return DownloadEntity.findAllData(DownloadEntity.class);
}
/** /**
* 通过下载链接获取下载实体 * 通过下载链接获取下载实体
*/ */
@ -99,20 +93,24 @@ public class DownloadReceiver implements IReceiver {
/** /**
* 下载任务是否存在 * 下载任务是否存在
*/ */
public boolean taskExists(String downloadUrl) { @Override public boolean taskExists(String downloadUrl) {
return DownloadEntity.findData(DownloadEntity.class, "downloadUrl=?", downloadUrl) != null; return DownloadEntity.findData(DownloadEntity.class, "downloadUrl=?", downloadUrl) != null;
} }
@Override public List<DownloadEntity> getTaskList() {
return DownloadEntity.findAllData(DownloadEntity.class);
}
/** /**
* 停止所有正在下载的任务 * 停止所有正在下载的任务
*/ */
public void stopAllTask() { @Override public void stopAllTask() {
final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP); final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP);
List<DownloadEntity> allEntity = ariaManager.getAllDownloadEntity(); List<DownloadEntity> allEntity = DbEntity.findAllData(DownloadEntity.class);
List<IDownloadCmd> stopCmds = new ArrayList<>(); List<AbsCmd> stopCmds = new ArrayList<>();
for (DownloadEntity entity : allEntity) { for (DownloadEntity entity : allEntity) {
if (entity.getState() == DownloadEntity.STATE_RUNNING) { if (entity.getState() == DownloadEntity.STATE_RUNNING) {
stopCmds.add(CommonUtil.createDownloadCmd(targetName, new DownloadTaskEntity(entity), stopCmds.add(CommonUtil.createCmd(targetName, new DownloadTaskEntity(entity),
CmdFactory.TASK_STOP)); CmdFactory.TASK_STOP));
} }
} }
@ -122,12 +120,12 @@ public class DownloadReceiver implements IReceiver {
/** /**
* 删除所有任务 * 删除所有任务
*/ */
public void cancelAllTask() { @Override public void removeAllTask() {
final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP); final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP);
List<DownloadEntity> allEntity = ariaManager.getAllDownloadEntity(); List<DownloadEntity> allEntity = DbEntity.findAllData(DownloadEntity.class);
List<IDownloadCmd> cancelCmds = new ArrayList<>(); List<AbsCmd> cancelCmds = new ArrayList<>();
for (DownloadEntity entity : allEntity) { for (DownloadEntity entity : allEntity) {
cancelCmds.add(CommonUtil.createDownloadCmd(targetName, new DownloadTaskEntity(entity), cancelCmds.add(CommonUtil.createCmd(targetName, new DownloadTaskEntity(entity),
CmdFactory.TASK_CANCEL)); CmdFactory.TASK_CANCEL));
} }
ariaManager.setCmds(cancelCmds).exe(); ariaManager.setCmds(cancelCmds).exe();

@ -17,27 +17,19 @@ package com.arialyy.aria.core.download;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.text.TextUtils; import android.text.TextUtils;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.RequestEnum; import com.arialyy.aria.core.RequestEnum;
import com.arialyy.aria.core.command.CmdFactory; import com.arialyy.aria.core.inf.AbsTarget;
import com.arialyy.aria.core.command.IDownloadCmd; import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
/** /**
* Created by lyy on 2016/12/5. * Created by lyy on 2016/12/5.
* https://github.com/AriaLyy/Aria * https://github.com/AriaLyy/Aria
*/ */
public class DownloadTarget { public class DownloadTarget extends AbsTarget<DownloadEntity, DownloadTaskEntity> {
DownloadEntity entity;
String targetName;
DownloadTaskEntity taskEntity;
public DownloadTarget(DownloadEntity entity, String targetName) { DownloadTarget(DownloadEntity entity, String targetName) {
this.entity = entity; this.entity = entity;
this.targetName = targetName; this.targetName = targetName;
taskEntity = new DownloadTaskEntity(entity); taskEntity = new DownloadTaskEntity(entity);
@ -50,7 +42,7 @@ public class DownloadTarget {
* @param header 头部value * @param header 头部value
*/ */
public DownloadTarget addHeader(@NonNull String key, @NonNull String header) { public DownloadTarget addHeader(@NonNull String key, @NonNull String header) {
taskEntity.headers.put(key, header); super._addHeader(key, header);
return this; return this;
} }
@ -60,12 +52,17 @@ public class DownloadTarget {
* @param headers Map<Key, Value> * @param headers Map<Key, Value>
*/ */
public DownloadTarget addHeaders(Map<String, String> headers) { public DownloadTarget addHeaders(Map<String, String> headers) {
if (headers != null && headers.size() > 0) { super._addHeaders(headers);
Set<String> keys = headers.keySet(); return this;
for (String key : keys) {
taskEntity.headers.put(key, headers.get(key));
}
} }
/**
* 设置请求类型
*
* @param requestEnum {@link RequestEnum}
*/
public DownloadTarget setRequestMode(RequestEnum requestEnum) {
super._setRequestMode(requestEnum);
return this; return this;
} }
@ -80,16 +77,6 @@ public class DownloadTarget {
return this; return this;
} }
/**
* 设置请求类型
*
* @param requestEnum {@link RequestEnum}
*/
public DownloadTarget setRequestMode(RequestEnum requestEnum) {
taskEntity.requestEnum = requestEnum;
return this;
}
/** /**
* 设置文件名 * 设置文件名
*/ */
@ -101,92 +88,16 @@ public class DownloadTarget {
return this; return this;
} }
/**
* 获取下载文件大小
*/
public long getFileSize() {
DownloadEntity entity = getDownloadEntity(this.entity.getDownloadUrl());
if (entity == null) {
throw new NullPointerException("下载管理器中没有改任务");
}
return entity.getFileSize();
}
/**
* 获取当前下载进度如果下載实体存在则返回当前进度
*/
public long getCurrentProgress() {
DownloadEntity entity = getDownloadEntity(this.entity.getDownloadUrl());
if (entity == null) {
throw new NullPointerException("下载管理器中没有改任务");
}
return entity.getCurrentProgress();
}
private DownloadEntity getDownloadEntity(String downloadUrl) { private DownloadEntity getDownloadEntity(String downloadUrl) {
CheckUtil.checkDownloadUrl(downloadUrl); CheckUtil.checkDownloadUrl(downloadUrl);
return DownloadEntity.findData(DownloadEntity.class, "downloadUrl=?", downloadUrl); return DownloadEntity.findData(DownloadEntity.class, "downloadUrl=?", downloadUrl);
} }
/**
* 添加任务
*/
public void add() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_CREATE))
.exe();
}
/**
* 开始下载
*/
public void start() {
List<IDownloadCmd> cmds = new ArrayList<>();
cmds.add(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_CREATE));
cmds.add(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_START));
AriaManager.getInstance(AriaManager.APP).setCmds(cmds).exe();
cmds.clear();
}
/**
* 停止下载
*/
public void stop() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_STOP))
.exe();
}
/**
* 恢复下载
*/
public void resume() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_START))
.exe();
}
/**
* 取消下载
*/
public void cancel() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createDownloadCmd(targetName, taskEntity, CmdFactory.TASK_CANCEL))
.exe();
}
/** /**
* 是否在下载 * 是否在下载
*/ */
public boolean isDownloading() { public boolean isDownloading() {
return AriaManager.getInstance(AriaManager.APP).getTaskQueue().getTask(entity).isDownloading(); return DownloadTaskQueue.getInstance().getTask(entity).isRunning();
}
/**
* 重新下载
*/
public void reStart() {
cancel();
start();
} }
} }

@ -25,7 +25,7 @@ import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.scheduler.DownloadSchedulers; import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.IDownloadSchedulers; import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration; import com.arialyy.aria.util.Configuration;
@ -133,6 +133,7 @@ public class DownloadTask implements ITask {
return mTargetName; return mTargetName;
} }
@Override
public void setTargetName(String targetName) { public void setTargetName(String targetName) {
this.mTargetName = targetName; this.mTargetName = targetName;
} }
@ -179,14 +180,14 @@ public class DownloadTask implements ITask {
} }
} }
static class Builder { public static class Builder {
DownloadTaskEntity taskEntity; DownloadTaskEntity taskEntity;
Handler outHandler; Handler outHandler;
int threadNum = 3; int threadNum = 3;
String targetName; String targetName;
Builder(String targetName, DownloadTaskEntity taskEntity) { public Builder(String targetName, DownloadTaskEntity taskEntity) {
CheckUtil.checkDownloadEntity(taskEntity.downloadEntity); CheckUtil.checkDownloadEntity(taskEntity.downloadEntity);
this.targetName = targetName; this.targetName = targetName;
this.taskEntity = taskEntity; this.taskEntity = taskEntity;
@ -195,9 +196,9 @@ public class DownloadTask implements ITask {
/** /**
* 设置自定义Handler处理下载状态时间 * 设置自定义Handler处理下载状态时间
* *
* @param schedulers {@link IDownloadSchedulers} * @param schedulers {@link ISchedulers}
*/ */
Builder setOutHandler(IDownloadSchedulers schedulers) { public Builder setOutHandler(ISchedulers schedulers) {
this.outHandler = new Handler(schedulers); this.outHandler = new Handler(schedulers);
return this; return this;
} }

@ -15,22 +15,22 @@
*/ */
package com.arialyy.aria.core.download; package com.arialyy.aria.core.download;
import com.arialyy.aria.core.RequestEnum; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
import java.util.HashMap;
import java.util.Map;
/** /**
* Created by Aria.Lao on 2017/1/23. * Created by Aria.Lao on 2017/1/23.
* 下载任务实体 * 下载任务实体
*/ */
public class DownloadTaskEntity implements ITaskEntity { public class DownloadTaskEntity extends ITaskEntity {
public DownloadEntity downloadEntity; public DownloadEntity downloadEntity;
public RequestEnum requestEnum = RequestEnum.GET;
public Map<String, String> headers = new HashMap<>();
public DownloadTaskEntity(DownloadEntity downloadEntity) { public DownloadTaskEntity(DownloadEntity downloadEntity) {
this.downloadEntity = downloadEntity; this.downloadEntity = downloadEntity;
} }
@Override public IEntity getEntity() {
return downloadEntity;
}
} }

@ -1,65 +0,0 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.download;
import android.content.Context;
import com.arialyy.aria.core.scheduler.IDownloadSchedulers;
/**
* Created by lyy on 2016/8/18.
* 任务工厂
*/
public class DownloadTaskFactory {
private static final String TAG = "DownloadTaskFactory";
private static final Object LOCK = new Object();
private static volatile DownloadTaskFactory INSTANCE = null;
private DownloadTaskFactory() {
}
public static DownloadTaskFactory getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new DownloadTaskFactory();
}
}
return INSTANCE;
}
/**
* 创建普通下载任务
*
* @param entity 下载任务实体{@link DownloadTaskEntity}
* @param schedulers {@link IDownloadSchedulers}
*/
public DownloadTask createTask(DownloadTaskEntity entity, IDownloadSchedulers schedulers) {
return createTask("", entity, schedulers);
}
/**
* @param entity 下载任务实体{@link DownloadTaskEntity}
* @param schedulers {@link IDownloadSchedulers}
*/
public DownloadTask createTask(String targetName, DownloadTaskEntity entity,
IDownloadSchedulers schedulers) {
DownloadTask.Builder builder = new DownloadTask.Builder(targetName, entity);
builder.setOutHandler(schedulers);
return builder.build();
}
}

@ -0,0 +1,175 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.inf;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.RequestEnum;
import com.arialyy.aria.core.command.AbsCmd;
import com.arialyy.aria.core.command.CmdFactory;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.CommonUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by Aria.Lao on 2017/2/28.
*/
public class AbsTarget<ENTITY extends IEntity, TASK_ENTITY extends ITaskEntity> {
protected ENTITY entity;
protected TASK_ENTITY taskEntity;
protected String targetName;
/**
* 获取任务文件大小
*
* @return -1没有找到该任务
*/
public long getFileSize() {
if (entity instanceof DownloadEntity) {
DownloadEntity entity = DbEntity.findData(DownloadEntity.class, "downloadUrl=?",
((DownloadEntity) this.entity).getDownloadUrl());
if (entity == null) {
throw new NullPointerException("没有找到该任务");
}
return entity.getFileSize();
} else if (entity instanceof UploadEntity) {
UploadEntity entity = DbEntity.findData(UploadEntity.class, "filePath=?",
((UploadEntity) this.entity).getFilePath());
if (entity == null) {
throw new NullPointerException("没有找到该任务");
}
return entity.getFileSize();
}
return -1;
}
/**
* 获取当前任务进度如果任务存在则返回当前进度
*
* @return -1没有找到该任务
*/
public long getCurrentProgress() {
if (entity instanceof DownloadEntity) {
DownloadEntity entity = DownloadEntity.findData(DownloadEntity.class, "downloadUrl=?",
((DownloadEntity) this.entity).getDownloadUrl());
if (entity == null) {
throw new NullPointerException("下载管理器中没有该任务");
}
return entity.getCurrentProgress();
} else if (entity instanceof UploadEntity) {
UploadEntity entity = DbEntity.findData(UploadEntity.class, "filePath=?",
((UploadEntity) this.entity).getFilePath());
if (entity == null) {
throw new NullPointerException("没有找到该任务");
}
return entity.getCurrentProgress();
}
return -1;
}
/**
* 给url请求添加头部
*
* @param key 头部key
* @param header 头部value
*/
protected void _addHeader(@NonNull String key, @NonNull String header) {
taskEntity.headers.put(key, header);
}
/**
* 给url请求添加头部
*
* @param headers Map<Key, Value>
*/
protected void _addHeaders(Map<String, String> headers) {
if (headers != null && headers.size() > 0) {
Set<String> keys = headers.keySet();
for (String key : keys) {
taskEntity.headers.put(key, headers.get(key));
}
}
}
/**
* 设置请求类型
*
* @param requestEnum {@link RequestEnum}
*/
protected void _setRequestMode(RequestEnum requestEnum) {
taskEntity.requestEnum = requestEnum;
}
/**
* 添加任务
*/
public void add() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_CREATE))
.exe();
}
/**
* 开始下载
*/
public void start() {
List<AbsCmd> cmds = new ArrayList<>();
cmds.add(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_CREATE));
cmds.add(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_START));
AriaManager.getInstance(AriaManager.APP).setCmds(cmds).exe();
cmds.clear();
}
/**
* 停止下载
*/
public void stop() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_STOP))
.exe();
}
/**
* 恢复下载
*/
public void resume() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_START))
.exe();
}
/**
* 取消下载
*/
public void cancel() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(CommonUtil.createCmd(targetName, taskEntity, CmdFactory.TASK_CANCEL))
.exe();
}
/**
* 重新下载
*/
public void reStart() {
cancel();
start();
}
}

@ -1,3 +1,18 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.inf; package com.arialyy.aria.core.inf;
import com.arialyy.aria.orm.Ignore; import com.arialyy.aria.orm.Ignore;
@ -44,4 +59,6 @@ public interface IEntity {
*/ */
@Ignore public static final int STATE_CANCEL = 7; @Ignore public static final int STATE_CANCEL = 7;
public int getState();
} }

@ -15,10 +15,12 @@
*/ */
package com.arialyy.aria.core.inf; package com.arialyy.aria.core.inf;
import java.util.List;
/** /**
* Created by Aria.Lao on 2017/2/6. * Created by Aria.Lao on 2017/2/6.
*/ */
public interface IReceiver { public interface IReceiver<ENTITY extends IEntity> {
/** /**
* Receiver 销毁 * Receiver 销毁
*/ */
@ -28,4 +30,26 @@ public interface IReceiver {
* 移除事件回调 * 移除事件回调
*/ */
public void removeSchedulerListener(); public void removeSchedulerListener();
/**
* 停止所有任务
*/
public void stopAllTask();
/**
* 删除所有任务
*/
public void removeAllTask();
/**
* 任务是否存在
*
* @param key 下载时为下载路径上传时为文件路径
*/
public boolean taskExists(String key);
/**
* 获取任务列表
*/
public List<ENTITY> getTaskList();
} }

@ -1,3 +1,18 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.inf; package com.arialyy.aria.core.inf;
/** /**
@ -33,4 +48,6 @@ public interface ITask {
public long getFileSize(); public long getFileSize();
public long getCurrentProgress(); public long getCurrentProgress();
public void setTargetName(String targetName);
} }

@ -1,9 +1,38 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.inf; package com.arialyy.aria.core.inf;
import com.arialyy.aria.core.RequestEnum;
import java.util.HashMap;
import java.util.Map;
/** /**
* Created by Aria.Lao on 2017/2/23. * Created by Aria.Lao on 2017/2/23.
*/ */
public interface ITaskEntity { public abstract class ITaskEntity {
/**
* http 请求头
*/
public Map<String, String> headers = new HashMap<>();
/**
* 网络请求类型
*/
public RequestEnum requestEnum = RequestEnum.GET;
public abstract IEntity getEntity();
} }

@ -1,6 +1,21 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.queue; package com.arialyy.aria.core.queue;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
@ -12,6 +27,6 @@ import com.arialyy.aria.core.queue.pool.ExecutePool;
*/ */
abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity, ENTITY extends IEntity> abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity, ENTITY extends IEntity>
implements ITaskQueue<TASK, TASK_ENTITY, ENTITY> { implements ITaskQueue<TASK, TASK_ENTITY, ENTITY> {
CachePool<DownloadTask> mCachePool = new CachePool<>(); CachePool<TASK> mCachePool = new CachePool<>();
ExecutePool<DownloadTask> mExecutePool = new ExecutePool<>(); ExecutePool<TASK> mExecutePool = new ExecutePool<>();
} }

@ -25,7 +25,6 @@ import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.queue.pool.CachePool; import com.arialyy.aria.core.queue.pool.CachePool;
import com.arialyy.aria.core.queue.pool.ExecutePool; import com.arialyy.aria.core.queue.pool.ExecutePool;
import com.arialyy.aria.core.scheduler.DownloadSchedulers; import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.download.DownloadTaskFactory;
import com.arialyy.aria.util.Configuration; import com.arialyy.aria.util.Configuration;
/** /**
@ -149,14 +148,14 @@ public class DownloadTaskQueue
} }
@Override public DownloadTask createTask(String target, DownloadTaskEntity entity) { @Override public DownloadTask createTask(String target, DownloadTaskEntity entity) {
DownloadTask task; DownloadTask task = null;
if (TextUtils.isEmpty(target)) { if (!TextUtils.isEmpty(target)) {
task = DownloadTaskFactory.getInstance().createTask(entity, DownloadSchedulers.getInstance()); task = (DownloadTask) TaskFactory.getInstance()
} else {
task = DownloadTaskFactory.getInstance()
.createTask(target, entity, DownloadSchedulers.getInstance()); .createTask(target, entity, DownloadSchedulers.getInstance());
}
mCachePool.putTask(task); mCachePool.putTask(task);
} else {
Log.e(TAG, "target name 为 null是!!");
}
return task; return task;
} }

@ -22,6 +22,9 @@ import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.core.upload.UploadTaskEntity;
/** /**
* Created by lyy on 2016/8/16. * Created by lyy on 2016/8/16.
@ -32,28 +35,28 @@ public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity,
/** /**
* 开始任务 * 开始任务
* *
* @param task {@link DownloadTask} * @param task {@link DownloadTask}{@link UploadTask}
*/ */
public void startTask(TASK task); public void startTask(TASK task);
/** /**
* 停止任务 * 停止任务
* *
* @param task {@link DownloadTask} * @param task {@link DownloadTask}{@link UploadTask}
*/ */
public void stopTask(TASK task); public void stopTask(TASK task);
/** /**
* 取消任务 * 取消任务
* *
* @param task {@link DownloadTask} * @param task {@link DownloadTask}{@link UploadTask}
*/ */
public void cancelTask(TASK task); public void cancelTask(TASK task);
/** /**
* 重试下载 * 重试下载
* *
* @param task {@link DownloadTask} * @param task {@link DownloadTask}{@link UploadTask}
*/ */
public void reTryStart(TASK task); public void reTryStart(TASK task);
@ -70,26 +73,26 @@ public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity,
public void setDownloadNum(int downloadNum); public void setDownloadNum(int downloadNum);
/** /**
* 创建一个新的下载任务创建时只是将新任务存储到缓存池 * 创建一个新的任务创建时只是将新任务存储到缓存池
* *
* @param entity 下载实体{@link DownloadTaskEntity} * @param entity 任务实体{@link DownloadTaskEntity}{@link UploadTaskEntity}
* @param targetName 生成该任务的对象 * @param targetName 生成该任务的对象
* @return {@link DownloadTask} * @return {@link DownloadTask}{@link UploadTask}
*/ */
public TASK createTask(String targetName, TASK_ENTITY entity); public TASK createTask(String targetName, TASK_ENTITY entity);
/** /**
* 通过下载链接从缓存池或任务池搜索下载任务如果缓存池或任务池都没有任务则创建新任务 * 通过工作实体缓存池或任务池搜索下载任务如果缓存池或任务池都没有任务则创建新任务
* *
* @param entity 下载实体{@link DownloadEntity} * @param entity 工作实体{@link DownloadEntity}{@link UploadEntity}
* @return {@link DownloadTask} * @return {@link DownloadTask}{@link UploadTask}
*/ */
public TASK getTask(ENTITY entity); public TASK getTask(ENTITY entity);
/** /**
* 通过下载链接删除任务 * 通过工作实体删除任务
* *
* @param entity 下载实体{@link DownloadEntity} * @param entity 工作实体{@link DownloadEntity}{@link UploadEntity}
*/ */
public void removeTask(ENTITY entity); public void removeTask(ENTITY entity);

@ -0,0 +1,92 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.queue;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.ITaskEntity;
import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.core.upload.UploadTaskEntity;
/**
* Created by lyy on 2016/8/18.
* 任务工厂
*/
public class TaskFactory {
private static final String TAG = "TaskFactory";
private static final Object LOCK = new Object();
private static volatile TaskFactory INSTANCE = null;
private TaskFactory() {
}
public static TaskFactory getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new TaskFactory();
}
}
return INSTANCE;
}
/**
* 创建任务
*
* @param entity 下载实体
* @param schedulers 对应的任务调度器
* @param <ENTITY> {@link DownloadTaskEntity}{@link UploadTaskEntity}
* @param <SCHEDULER> {@link DownloadSchedulers}
* @return {@link DownloadTask}{@link UploadTask}
*/
<ENTITY extends ITaskEntity, SCHEDULER extends ISchedulers> ITask createTask(
String targetName, ENTITY entity, SCHEDULER schedulers) {
if (entity instanceof DownloadTaskEntity) {
return createDownloadTask(targetName, (DownloadTaskEntity) entity, schedulers);
} else if (entity instanceof UploadTaskEntity) {
return createUploadTask(targetName, (UploadTaskEntity) entity, schedulers);
} return null;
}
/**
* @param entity 上传任务实体{@link UploadTaskEntity}
* @param schedulers {@link ISchedulers}
*/
private UploadTask createUploadTask(String targetName, UploadTaskEntity entity,
ISchedulers schedulers) {
UploadTask.Builder builder = new UploadTask.Builder();
builder.setTargetName(targetName);
builder.setUploadTaskEntity(entity);
builder.setOutHandler(schedulers);
return builder.build();
}
/**
* @param entity 下载任务实体{@link DownloadTaskEntity}
* @param schedulers {@link ISchedulers}
*/
private DownloadTask createDownloadTask(String targetName, DownloadTaskEntity entity,
ISchedulers schedulers) {
DownloadTask.Builder builder = new DownloadTask.Builder(targetName, entity);
builder.setOutHandler(schedulers);
return builder.build();
}
}

@ -0,0 +1,120 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.queue;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.aria.core.scheduler.UploadSchedulers;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.core.upload.UploadTaskEntity;
/**
* Created by Aria.Lao on 2017/2/27.
* 上传任务队列
*/
public class UploadTaskQueue extends AbsTaskQueue<UploadTask, UploadTaskEntity, UploadEntity> {
private static final String TAG = "UploadTaskQueue";
private static volatile UploadTaskQueue INSTANCE = null;
private static final Object LOCK = new Object();
public static UploadTaskQueue getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new UploadTaskQueue();
}
}
return INSTANCE;
}
@Override public void startTask(UploadTask task) {
if (mExecutePool.putTask(task)) {
mCachePool.removeTask(task);
//task.getEntity().setFailNum(0);
task.start();
}
}
@Override public void stopTask(UploadTask task) {
if (!task.isRunning()) Log.w(TAG, "停止任务失败,【任务已经停止】");
if (mExecutePool.removeTask(task)) {
task.stop();
} else {
task.stop();
Log.w(TAG, "停止任务失败,【任务已经停止】");
}
}
@Override public void cancelTask(UploadTask task) {
task.cancel();
}
@Override public void reTryStart(UploadTask task) {
if (task == null) {
Log.w(TAG, "重试下载失败,task 为null");
return;
}
if (!task.isRunning()) {
task.start();
} else {
Log.w(TAG, "任务没有完全停止,重试下载失败");
}
}
@Override public int size() {
return mExecutePool.size();
}
@Override public void setDownloadNum(int downloadNum) {
}
@Override public UploadTask createTask(String targetName, UploadTaskEntity entity) {
UploadTask task = null;
if (!TextUtils.isEmpty(targetName)) {
task = (UploadTask) TaskFactory.getInstance()
.createTask(targetName, entity, UploadSchedulers.getInstance());
mCachePool.putTask(task);
} else {
Log.e(TAG, "target name 为 null是!!");
}
return task;
}
@Override public UploadTask getTask(UploadEntity entity) {
UploadTask task = mExecutePool.getTask(entity.getFilePath());
if (task == null) {
task = mCachePool.getTask(entity.getFilePath());
}
return task;
}
@Override public void removeTask(UploadEntity entity) {
UploadTask task = mExecutePool.getTask(entity.getFilePath());
if (task != null) {
Log.d(TAG, "从执行池删除任务,删除" + (mExecutePool.removeTask(task) ? "成功" : "失败"));
}
task = mCachePool.getTask(entity.getFilePath());
if (task != null) {
Log.d(TAG, "从缓存池删除任务,删除" + (mCachePool.removeTask(task) ? "成功" : "失败"));
}
}
@Override public UploadTask getNextTask() {
return mCachePool.pollTask();
}
}

@ -19,7 +19,6 @@ package com.arialyy.aria.core.queue.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.queue.IPool;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -34,7 +33,6 @@ public class CachePool<TASK extends ITask> implements IPool<TASK> {
private static final String TAG = "CachePool"; private static final String TAG = "CachePool";
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private static final int MAX_NUM = Integer.MAX_VALUE; //最大下载任务数 private static final int MAX_NUM = Integer.MAX_VALUE; //最大下载任务数
private static volatile CachePool INSTANCE = null;
private static final long TIME_OUT = 1000; private static final long TIME_OUT = 1000;
private Map<String, TASK> mCacheArray; private Map<String, TASK> mCacheArray;
private LinkedBlockingQueue<TASK> mCacheQueue; private LinkedBlockingQueue<TASK> mCacheQueue;
@ -44,15 +42,6 @@ public class CachePool<TASK extends ITask> implements IPool<TASK> {
mCacheArray = new HashMap<>(); mCacheArray = new HashMap<>();
} }
//public static CachePool getInstance() {
// if (INSTANCE == null) {
// synchronized (LOCK) {
// INSTANCE = new CachePool();
// }
// }
// return INSTANCE;
//}
@Override public boolean putTask(TASK task) { @Override public boolean putTask(TASK task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {

@ -19,7 +19,6 @@ package com.arialyy.aria.core.queue.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.queue.IPool;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration; import com.arialyy.aria.util.Configuration;
import java.util.HashMap; import java.util.HashMap;
@ -35,7 +34,6 @@ public class ExecutePool<TASK extends ITask> implements IPool<TASK> {
private static final String TAG = "ExecutePool"; private static final String TAG = "ExecutePool";
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private static final long TIME_OUT = 1000; private static final long TIME_OUT = 1000;
private static volatile ExecutePool INSTANCE = null;
private ArrayBlockingQueue<TASK> mExecuteQueue; private ArrayBlockingQueue<TASK> mExecuteQueue;
private Map<String, TASK> mExecuteArray; private Map<String, TASK> mExecuteArray;
private int mSize; private int mSize;
@ -46,15 +44,6 @@ public class ExecutePool<TASK extends ITask> implements IPool<TASK> {
mExecuteArray = new HashMap<>(); mExecuteArray = new HashMap<>();
} }
//public static ExecutePool getInstance() {
// if (INSTANCE == null) {
// synchronized (LOCK) {
// INSTANCE = new ExecutePool();
// }
// }
// return INSTANCE;
//}
@Override public boolean putTask(TASK task) { @Override public boolean putTask(TASK task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {

@ -15,7 +15,7 @@
*/ */
package com.arialyy.aria.core.queue; package com.arialyy.aria.core.queue.pool;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;

@ -19,8 +19,7 @@ package com.arialyy.aria.core.scheduler;
import android.os.CountDownTimer; import android.os.CountDownTimer;
import android.os.Message; import android.os.Message;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager; import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.queue.ITaskQueue;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.util.Configuration; import com.arialyy.aria.util.Configuration;
@ -33,39 +32,8 @@ import java.util.concurrent.ConcurrentHashMap;
* Created by lyy on 2016/8/16. * Created by lyy on 2016/8/16.
* 任务下载器提供抽象的方法供具体的实现类操作 * 任务下载器提供抽象的方法供具体的实现类操作
*/ */
public class DownloadSchedulers implements IDownloadSchedulers { public class DownloadSchedulers implements ISchedulers<DownloadTask> {
/**
* 任务预加载
*/
public static final int PRE = 0;
/**
* 任务开始
*/
public static final int START = 1;
/**
* 任务停止
*/
public static final int STOP = 2;
/**
* 任务失败
*/
public static final int FAIL = 3;
/**
* 任务取消
*/
public static final int CANCEL = 4;
/**
* 任务完成
*/
public static final int COMPLETE = 5;
/**
* 下载中
*/
public static final int RUNNING = 6;
/**
* 恢复下载
*/
public static final int RESUME = 7;
private static final String TAG = "DownloadSchedulers"; private static final String TAG = "DownloadSchedulers";
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private static volatile DownloadSchedulers INSTANCE = null; private static volatile DownloadSchedulers INSTANCE = null;
@ -73,36 +41,34 @@ public class DownloadSchedulers implements IDownloadSchedulers {
/** /**
* 下载器任务监听 * 下载器任务监听
*/ */
Map<String, OnSchedulerListener> mSchedulerListeners = new ConcurrentHashMap<>(); private Map<String, OnSchedulerListener<DownloadTask>> mSchedulerListeners =
ITaskQueue mQueue; new ConcurrentHashMap<>();
private DownloadTaskQueue mQueue;
private DownloadSchedulers() { private DownloadSchedulers() {
mQueue = AriaManager.getInstance(AriaManager.APP).getTaskQueue(); mQueue = DownloadTaskQueue.getInstance();
} }
public static DownloadSchedulers getInstance() { public static DownloadSchedulers getInstance() {
if (INSTANCE == null) { if (INSTANCE == null) {
synchronized (LOCK) { synchronized (LOCK) {
//INSTANCE = new DownloadSchedulers(queue);
INSTANCE = new DownloadSchedulers(); INSTANCE = new DownloadSchedulers();
} }
} }
return INSTANCE; return INSTANCE;
} }
@Override @Override public void addSchedulerListener(String targetName,
public void addSchedulerListener(String targetName, OnSchedulerListener schedulerListener) { OnSchedulerListener<DownloadTask> schedulerListener) {
mSchedulerListeners.put(targetName, schedulerListener); mSchedulerListeners.put(targetName, schedulerListener);
} }
@Override @Override public void removeSchedulerListener(String targetName,
public void removeSchedulerListener(String targetName, OnSchedulerListener schedulerListener) { OnSchedulerListener<DownloadTask> schedulerListener) {
//OnSchedulerListener listener = mSchedulerListeners.get(target.getClass().getName());
//mSchedulerListeners.remove(listener);
//该内存溢出解决方案:http://stackoverflow.com/questions/14585829/how-safe-is-to-delete-already-removed-concurrenthashmap-element //该内存溢出解决方案:http://stackoverflow.com/questions/14585829/how-safe-is-to-delete-already-removed-concurrenthashmap-element
for (Iterator<Map.Entry<String, OnSchedulerListener>> iter = for (Iterator<Map.Entry<String, OnSchedulerListener<DownloadTask>>> iter =
mSchedulerListeners.entrySet().iterator(); iter.hasNext(); ) { mSchedulerListeners.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, OnSchedulerListener> entry = iter.next(); Map.Entry<String, OnSchedulerListener<DownloadTask>> entry = iter.next();
if (entry.getKey().equals(targetName)) iter.remove(); if (entry.getKey().equals(targetName)) iter.remove();
} }
} }
@ -120,12 +86,12 @@ public class DownloadSchedulers implements IDownloadSchedulers {
case CANCEL: case CANCEL:
mQueue.removeTask(entity); mQueue.removeTask(entity);
if (mQueue.size() < Configuration.getInstance().getDownloadNum()) { if (mQueue.size() < Configuration.getInstance().getDownloadNum()) {
startNextTask(entity); startNextTask();
} }
break; break;
case COMPLETE: case COMPLETE:
mQueue.removeTask(entity); mQueue.removeTask(entity);
startNextTask(entity); startNextTask();
break; break;
case FAIL: case FAIL:
mQueue.removeTask(entity); mQueue.removeTask(entity);
@ -152,7 +118,7 @@ public class DownloadSchedulers implements IDownloadSchedulers {
} }
} }
private void callback(int state, DownloadTask task, OnSchedulerListener listener) { private void callback(int state, DownloadTask task, OnSchedulerListener<DownloadTask> listener) {
if (listener != null) { if (listener != null) {
if (task == null) { if (task == null) {
Log.e(TAG, "TASK 为null,回调失败"); Log.e(TAG, "TASK 为null,回调失败");
@ -192,7 +158,7 @@ public class DownloadSchedulers implements IDownloadSchedulers {
* *
* @param entity 失败实体 * @param entity 失败实体
*/ */
@Override public void handleFailTask(final DownloadEntity entity) { private void handleFailTask(final DownloadEntity entity) {
final Configuration config = Configuration.getInstance(); final Configuration config = Configuration.getInstance();
CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) { CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) {
@Override public void onTick(long millisUntilFinished) { @Override public void onTick(long millisUntilFinished) {
@ -209,7 +175,7 @@ public class DownloadSchedulers implements IDownloadSchedulers {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
startNextTask(entity); startNextTask();
} }
} }
}; };
@ -218,10 +184,8 @@ public class DownloadSchedulers implements IDownloadSchedulers {
/** /**
* 启动下一个任务条件任务停止取消下载任务完成 * 启动下一个任务条件任务停止取消下载任务完成
*
* @param entity 通过Handler传递的下载实体
*/ */
@Override public void startNextTask(DownloadEntity entity) { private void startNextTask() {
DownloadTask newTask = mQueue.getNextTask(); DownloadTask newTask = mQueue.getNextTask();
if (newTask == null) { if (newTask == null) {
Log.w(TAG, "没有下一任务"); Log.w(TAG, "没有下一任务");

@ -18,12 +18,45 @@ package com.arialyy.aria.core.scheduler;
import android.os.Handler; import android.os.Handler;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.ITask;
/** /**
* Created by AriaLyy@outlook.com on 2016/11/2. * Created by AriaLyy@outlook.com on 2016/11/2.
* 下载调度器接口 * 调度器功能接口
*/ */
public interface IDownloadSchedulers extends Handler.Callback { public interface ISchedulers<Task extends ITask> extends Handler.Callback {
/**
* 任务预加载
*/
public static final int PRE = 0;
/**
* 任务开始
*/
public static final int START = 1;
/**
* 任务停止
*/
public static final int STOP = 2;
/**
* 任务失败
*/
public static final int FAIL = 3;
/**
* 任务取消
*/
public static final int CANCEL = 4;
/**
* 任务完成
*/
public static final int COMPLETE = 5;
/**
* 任务处理中
*/
public static final int RUNNING = 6;
/**
* 恢复任务
*/
public static final int RESUME = 7;
/** /**
* 注册下载器监听一个观察者只能注册一次监听 * 注册下载器监听一个观察者只能注册一次监听
@ -31,25 +64,12 @@ public interface IDownloadSchedulers extends Handler.Callback {
* @param targetName 观察者创建该监听器的对象类名 * @param targetName 观察者创建该监听器的对象类名
* @param schedulerListener {@link OnSchedulerListener} * @param schedulerListener {@link OnSchedulerListener}
*/ */
public void addSchedulerListener(String targetName, OnSchedulerListener schedulerListener); public void addSchedulerListener(String targetName, OnSchedulerListener<Task> schedulerListener);
/** /**
* @param targetName 观察者创建该监听器的对象类名 * @param targetName 观察者创建该监听器的对象类名
* 取消注册监听器 * 取消注册监听器
*/ */
public void removeSchedulerListener(String targetName, OnSchedulerListener schedulerListener); public void removeSchedulerListener(String targetName, OnSchedulerListener<Task> schedulerListener);
/**
* 处理下载任务下载失败的情形
*
* @param entity 下载实体
*/
public void handleFailTask(DownloadEntity entity);
/**
* 启动下一个任务条件任务停止取消下载任务完成
*
* @param entity 通过Handler传递的下载实体
*/
public void startNextTask(DownloadEntity entity);
} }

@ -15,49 +15,49 @@
*/ */
package com.arialyy.aria.core.scheduler; package com.arialyy.aria.core.scheduler;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.inf.ITask;
/** /**
* Target处理任务监听 * Target处理任务监听
*/ */
public interface OnSchedulerListener { public interface OnSchedulerListener<TASK extends ITask> {
/** /**
* 任务预加载 * 任务预加载
*/ */
public void onTaskPre(DownloadTask task); public void onTaskPre(TASK task);
/** /**
* 任务恢复下载 * 任务恢复下载
*/ */
public void onTaskResume(DownloadTask task); public void onTaskResume(TASK task);
/** /**
* 任务开始 * 任务开始
*/ */
public void onTaskStart(DownloadTask task); public void onTaskStart(TASK task);
/** /**
* 任务停止 * 任务停止
*/ */
public void onTaskStop(DownloadTask task); public void onTaskStop(TASK task);
/** /**
* 任务取消 * 任务取消
*/ */
public void onTaskCancel(DownloadTask task); public void onTaskCancel(TASK task);
/** /**
* 任务下载失败 * 任务下载失败
*/ */
public void onTaskFail(DownloadTask task); public void onTaskFail(TASK task);
/** /**
* 任务完成 * 任务完成
*/ */
public void onTaskComplete(DownloadTask task); public void onTaskComplete(TASK task);
/** /**
* 任务执行中 * 任务执行中
*/ */
public void onTaskRunning(DownloadTask task); public void onTaskRunning(TASK task);
} }

@ -0,0 +1,185 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.scheduler;
import android.os.CountDownTimer;
import android.os.Message;
import android.util.Log;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.util.Configuration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by Aria.Lao on 2017/2/27.
* 上传任务调度器
*/
public class UploadSchedulers implements ISchedulers<UploadTask> {
private static final String TAG = "UploadSchedulers";
private static final Object LOCK = new Object();
private static volatile UploadSchedulers INSTANCE = null;
private Map<String, OnSchedulerListener<UploadTask>> mSchedulerListeners =
new ConcurrentHashMap<>();
private UploadTaskQueue mQueue;
private UploadSchedulers() {
mQueue = UploadTaskQueue.getInstance();
}
public static UploadSchedulers getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new UploadSchedulers();
}
}
return INSTANCE;
}
@Override public void addSchedulerListener(String targetName,
OnSchedulerListener<UploadTask> schedulerListener) {
mSchedulerListeners.put(targetName, schedulerListener);
}
@Override public void removeSchedulerListener(String targetName,
OnSchedulerListener<UploadTask> schedulerListener) {
for (Iterator<Map.Entry<String, OnSchedulerListener<UploadTask>>> iter =
mSchedulerListeners.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, OnSchedulerListener<UploadTask>> entry = iter.next();
if (entry.getKey().equals(targetName)) iter.remove();
}
}
private void handleFailTask(final UploadEntity entity) {
final Configuration config = Configuration.getInstance();
CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) {
@Override public void onTick(long millisUntilFinished) {
}
@Override public void onFinish() {
if (entity.getFailNum() <= config.getReTryNum()) {
UploadTask task = mQueue.getTask(entity);
mQueue.reTryStart(task);
try {
Thread.sleep(config.getReTryInterval());
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
startNextTask();
}
}
};
timer.start();
}
private void startNextTask() {
UploadTask newTask = mQueue.getNextTask();
if (newTask == null) {
Log.w(TAG, "没有下一任务");
return;
}
if (newTask.getUploadEntity().getState() == IEntity.STATE_WAIT) {
mQueue.startTask(newTask);
}
}
/**
* 回调
*
* @param state 状态
*/
private void callback(int state, UploadTask task) {
if (mSchedulerListeners.size() > 0) {
//if (!TextUtils.isEmpty(task.getTargetName())) {
// callback(state, task, mSchedulerListeners.get(task.getTargetName()));
//}
Set<String> keys = mSchedulerListeners.keySet();
for (String key : keys) {
callback(state, task, mSchedulerListeners.get(key));
}
}
}
private void callback(int state, UploadTask task, OnSchedulerListener<UploadTask> listener) {
if (listener != null) {
if (task == null) {
Log.e(TAG, "TASK 为null,回调失败");
return;
}
switch (state) {
case RUNNING:
listener.onTaskRunning(task);
break;
case START:
listener.onTaskStart(task);
break;
case STOP:
listener.onTaskStop(task);
break;
case RESUME:
listener.onTaskResume(task);
break;
case PRE:
listener.onTaskPre(task);
break;
case CANCEL:
listener.onTaskCancel(task);
break;
case COMPLETE:
listener.onTaskComplete(task);
break;
case FAIL:
listener.onTaskFail(task);
break;
}
}
}
@Override public boolean handleMessage(Message msg) {
UploadTask task = (UploadTask) msg.obj;
if (task == null) {
Log.e(TAG, "请传入上传任务");
return true;
}
callback(msg.what, task);
UploadEntity entity = task.getUploadEntity();
switch (msg.what) {
case STOP:
case CANCEL:
mQueue.removeTask(entity);
if (mQueue.size() < Configuration.getInstance().getDownloadNum()) {
startNextTask();
}
break;
case COMPLETE:
mQueue.removeTask(entity);
startNextTask();
break;
case FAIL:
mQueue.removeTask(entity);
handleFailTask(entity);
break;
}
return true;
}
}

@ -1,18 +1,73 @@
package com.arialyy.aria.core.upload; package com.arialyy.aria.core.upload;
import com.arialyy.aria.core.download.DownloadEntity; import android.os.Parcel;
import android.os.Parcelable;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.orm.DbEntity; import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.orm.Ignore;
/** /**
* Created by Aria.Lao on 2017/2/9. * Created by Aria.Lao on 2017/2/9.
* 上传文件实体 * 上传文件实体
*/ */
public class UploadEntity implements IEntity{ public class UploadEntity extends DbEntity implements IEntity, Parcelable {
private String filePath; //文件路径 private String filePath; //文件路径
private String fileName; //文件名 private String fileName; //文件名
private long fileSize; //文件大小 private long fileSize; //文件大小
private int state = STATE_WAIT;
private long currentProgress = 0;
private boolean isComplete = false;
@Ignore private long speed = 0; //下载速度
@Ignore private int failNum = 0;
public boolean isComplete() {
return isComplete;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
public long getCurrentProgress() {
return currentProgress;
}
public void setCurrentProgress(long currentProgress) {
this.currentProgress = currentProgress;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public int getFailNum() {
return failNum;
}
public void setFailNum(int failNum) {
this.failNum = failNum;
}
@Override public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getFilePath() { public String getFilePath() {
return filePath; return filePath;
@ -30,4 +85,42 @@ public class UploadEntity implements IEntity{
this.fileName = fileName; this.fileName = fileName;
} }
public UploadEntity() {
}
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.filePath);
dest.writeString(this.fileName);
dest.writeLong(this.fileSize);
dest.writeInt(this.state);
dest.writeLong(this.currentProgress);
dest.writeByte(this.isComplete ? (byte) 1 : (byte) 0);
dest.writeLong(this.speed);
dest.writeInt(this.failNum);
}
protected UploadEntity(Parcel in) {
this.filePath = in.readString();
this.fileName = in.readString();
this.fileSize = in.readLong();
this.state = in.readInt();
this.currentProgress = in.readLong();
this.isComplete = in.readByte() != 0;
this.speed = in.readLong();
this.failNum = in.readInt();
}
@Ignore public static final Creator<UploadEntity> CREATOR = new Creator<UploadEntity>() {
@Override public UploadEntity createFromParcel(Parcel source) {
return new UploadEntity(source);
}
@Override public UploadEntity[] newArray(int size) {
return new UploadEntity[size];
}
};
} }

@ -15,19 +15,110 @@
*/ */
package com.arialyy.aria.core.upload; package com.arialyy.aria.core.upload;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.command.AbsCmd;
import com.arialyy.aria.core.command.CmdFactory;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.IReceiver; import com.arialyy.aria.core.inf.IReceiver;
import com.arialyy.aria.core.scheduler.OnSchedulerListener;
import com.arialyy.aria.core.scheduler.UploadSchedulers;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/** /**
* Created by Aria.Lao on 2017/2/6. * Created by Aria.Lao on 2017/2/6.
* 上传功能接收器 * 上传功能接收器
*/ */
public class UploadReceiver implements IReceiver { public class UploadReceiver implements IReceiver<UploadEntity> {
private static final String TAG = "DownloadReceiver";
public String targetName;
public OnSchedulerListener<UploadTask> listener;
/**
* 加载任务
*
* @param filePath 文件地址
*/
public UploadTarget load(@NonNull String filePath) {
CheckUtil.checkUploadPath(filePath);
UploadEntity entity = UploadEntity.findData(UploadEntity.class, "filePath=?", filePath);
if (entity == null) {
entity = new UploadEntity();
}
entity.setFilePath(filePath);
return new UploadTarget(entity, targetName);
}
/**
* 通过上传路径获取上传实体
*/
public UploadEntity getUploadEntity(String filePath) {
CheckUtil.checkUploadPath(filePath);
return DbEntity.findData(UploadEntity.class, "filePath=?", filePath);
}
/**
* 下载任务是否存在
*/
@Override public boolean taskExists(String filePath) {
return DbEntity.findData(UploadEntity.class, "filePath=?", filePath) != null;
}
@Override public List<UploadEntity> getTaskList() {
return DbEntity.findAllData(UploadEntity.class);
}
@Override public void stopAllTask() {
List<UploadEntity> allEntity = DbEntity.findAllData(UploadEntity.class);
List<AbsCmd> stopCmds = new ArrayList<>();
for (UploadEntity entity : allEntity) {
if (entity.getState() == IEntity.STATE_RUNNING) {
stopCmds.add(
CommonUtil.createCmd(targetName, new UploadTaskEntity(entity), CmdFactory.TASK_STOP));
}
}
AriaManager.getInstance(AriaManager.APP).setCmds(stopCmds).exe();
}
@Override public void removeAllTask() {
final AriaManager am = AriaManager.getInstance(AriaManager.APP);
List<UploadEntity> allEntity = DbEntity.findAllData(UploadEntity.class);
List<AbsCmd> cancelCmds = new ArrayList<>();
for (UploadEntity entity : allEntity) {
cancelCmds.add(
CommonUtil.createCmd(targetName, new UploadTaskEntity(entity), CmdFactory.TASK_CANCEL));
}
am.setCmds(cancelCmds).exe();
Set<String> keys = am.getReceiver().keySet();
for (String key : keys) {
IReceiver receiver = am.getReceiver().get(key);
receiver.removeSchedulerListener();
am.getReceiver().remove(key);
}
}
@Override public void destroy() { @Override public void destroy() {
targetName = null;
listener = null;
}
/**
* 添加调度器回调
*/
public UploadReceiver addSchedulerListener(OnSchedulerListener<UploadTask> listener) {
this.listener = listener;
UploadSchedulers.getInstance().addSchedulerListener(targetName, listener);
return this;
} }
@Override public void removeSchedulerListener() { @Override public void removeSchedulerListener() {
if (listener != null) {
UploadSchedulers.getInstance().removeSchedulerListener(targetName, listener);
}
} }
} }

@ -0,0 +1,115 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.upload;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.RequestEnum;
import com.arialyy.aria.core.inf.AbsTarget;
import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.orm.DbEntity;
import java.util.Map;
/**
* Created by Aria.Lao on 2017/2/28.
*/
public class UploadTarget extends AbsTarget<UploadEntity, UploadTaskEntity> {
UploadTarget(UploadEntity entity, String targetName) {
this.entity = entity;
this.targetName = targetName;
taskEntity = new UploadTaskEntity(entity);
}
/**
* 设置上传路径
*
* @param uploadUrl 上传路径
*/
public UploadTarget setUploadUrl(@NonNull String uploadUrl) {
taskEntity.uploadUrl = uploadUrl;
return this;
}
/**
* 设置服务器需要的附件key
*
* @param attachment 附件key
*/
public UploadTarget setAttachment(@NonNull String attachment) {
taskEntity.attachment = attachment;
return this;
}
/**
* 设置文件名
*/
public UploadTarget setFileName(String fileName) {
entity.setFileName(fileName);
return this;
}
/**
* 设置上传文件类型
*
* @param contentType <code>"multipart/form-data"<code/>
*/
public UploadTarget setContentType(String contentType) {
taskEntity.contentType = contentType;
return this;
}
/**
* 给url请求添加头部
*
* @param key 头部key
* @param header 头部value
*/
public UploadTarget addHeader(@NonNull String key, @NonNull String header) {
super._addHeader(key, header);
return this;
}
/**
* 给url请求添加头部
*
* @param headers Map<Key, Value>
*/
public UploadTarget addHeaders(Map<String, String> headers) {
super._addHeaders(headers);
return this;
}
/**
* 设置请求类型
*
* @param requestEnum {@link RequestEnum}
*/
public UploadTarget setRequestMode(RequestEnum requestEnum) {
super._setRequestMode(requestEnum);
return this;
}
private UploadEntity getDownloadEntity(@NonNull String filePath) {
return DbEntity.findData(UploadEntity.class, "filePath=?", filePath);
}
/**
* 是否在下载
*/
public boolean isUploading() {
return UploadTaskQueue.getInstance().getTask(entity).isRunning();
}
}

@ -1,22 +1,43 @@
package com.arialyy.aria.core.upload; package com.arialyy.aria.core.upload;
import android.content.Intent;
import android.os.Handler; import android.os.Handler;
import android.util.Log;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration;
import java.lang.ref.WeakReference;
/** /**
* Created by Aria.Lao on 2017/2/23. * Created by Aria.Lao on 2017/2/23.
* 上传任务 * 上传任务
*/ */
public class UploadTask implements ITask { public class UploadTask implements ITask {
private static final String TAG = "UploadTask";
private Handler mOutHandler; private Handler mOutHandler;
private UploadTaskEntity mTaskEntity; private UploadTaskEntity mTaskEntity;
private UploadEntity mUploadEntity; private UploadEntity mUploadEntity;
private String mTargetName;
private UploadUtil mUtil;
private UListener mListener;
UploadTask(UploadTaskEntity taskEntity, Handler outHandler) { UploadTask(UploadTaskEntity taskEntity, Handler outHandler) {
mTaskEntity = taskEntity; mTaskEntity = taskEntity;
mOutHandler = outHandler; mOutHandler = outHandler;
mUploadEntity = mTaskEntity.uploadEntity; mUploadEntity = mTaskEntity.uploadEntity;
mListener = new UListener(mOutHandler, this);
mUtil = new UploadUtil(mTaskEntity, mListener);
}
@Override public void setTargetName(String targetName) {
mTargetName = targetName;
} }
@Override public String getKey() { @Override public String getKey() {
@ -27,12 +48,23 @@ public class UploadTask implements ITask {
return false; return false;
} }
public UploadEntity getUploadEntity() {
return mUploadEntity;
}
@Override public IEntity getEntity() { @Override public IEntity getEntity() {
return mUploadEntity; return mUploadEntity;
} }
@Override public void start() { @Override public void start() {
if (mUtil.isRunning()) {
Log.d(TAG, "任务正在下载");
} else {
if (mListener == null) {
mListener = new UploadTask.UListener(mOutHandler, this);
}
mUtil.start();
}
} }
@Override public void stop() { @Override public void stop() {
@ -40,75 +72,175 @@ public class UploadTask implements ITask {
} }
@Override public void cancel() { @Override public void cancel() {
if (mUtil.isRunning()) {
mUtil.cancel();
} else {
// 如果任务不是下载状态
mUtil.cancel();
mUploadEntity.deleteData();
if (mOutHandler != null) {
mOutHandler.obtainMessage(DownloadSchedulers.CANCEL, this).sendToTarget();
}
//发送取消下载的广播
Intent intent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), Aria.ACTION_CANCEL);
intent.putExtra(Aria.ENTITY, mUploadEntity);
AriaManager.APP.sendBroadcast(intent);
}
}
public String getTargetName() {
return mTargetName;
} }
@Override public long getSpeed() { @Override public long getSpeed() {
return 0; return mUploadEntity.getSpeed();
} }
@Override public long getFileSize() { @Override public long getFileSize() {
return 0; return mUploadEntity.getFileSize();
} }
@Override public long getCurrentProgress() { @Override public long getCurrentProgress() {
return 0; return mUploadEntity.getCurrentProgress();
} }
private static class UListener extends UploadListener{ private static class UListener extends UploadListener {
@Override public void onPre() { WeakReference<Handler> outHandler;
WeakReference<UploadTask> task;
long lastLen = 0; //上一次发送长度
long lastTime = 0;
long INTERVAL_TIME = 1000; //1m更新周期
boolean isFirst = true;
UploadEntity entity;
Intent sendIntent;
UListener(Handler outHandle, UploadTask task) {
this.outHandler = new WeakReference<>(outHandle);
this.task = new WeakReference<>(task);
entity = this.task.get().getUploadEntity();
sendIntent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), Aria.ACTION_RUNNING);
sendIntent.putExtra(Aria.ENTITY, entity);
} }
@Override public void onStart(long fileSize) { @Override public void onPre() {
entity.setState(IEntity.STATE_PRE);
sendIntent(Aria.ACTION_PRE, -1);
sendInState2Target(ISchedulers.PRE);
}
@Override public void onStart(long fileSize) {
entity.setFileSize(fileSize);
entity.setState(IEntity.STATE_RUNNING);
sendIntent(Aria.ACTION_PRE, -1);
sendInState2Target(ISchedulers.START);
} }
@Override public void onResume(long resumeLocation) { @Override public void onResume(long resumeLocation) {
entity.setState(DownloadEntity.STATE_RUNNING);
sendInState2Target(DownloadSchedulers.RESUME);
sendIntent(Aria.ACTION_RESUME, resumeLocation);
} }
@Override public void onStop(long stopLocation) { @Override public void onStop(long stopLocation) {
entity.setState(DownloadEntity.STATE_STOP);
entity.setSpeed(0);
sendInState2Target(DownloadSchedulers.STOP);
sendIntent(Aria.ACTION_STOP, stopLocation);
} }
@Override public void onProgress(long currentLocation) { @Override public void onProgress(long currentLocation) {
if (System.currentTimeMillis() - lastTime > INTERVAL_TIME) {
long speed = currentLocation - lastLen;
sendIntent.putExtra(Aria.CURRENT_LOCATION, currentLocation);
sendIntent.putExtra(Aria.CURRENT_SPEED, speed);
lastTime = System.currentTimeMillis();
if (isFirst) {
entity.setSpeed(0);
isFirst = false;
} else {
entity.setSpeed(speed);
}
entity.setCurrentProgress(currentLocation);
lastLen = currentLocation;
sendInState2Target(DownloadSchedulers.RUNNING);
AriaManager.APP.sendBroadcast(sendIntent);
}
} }
@Override public void onCancel() { @Override public void onCancel() {
entity.setState(DownloadEntity.STATE_CANCEL);
sendInState2Target(DownloadSchedulers.CANCEL);
sendIntent(Aria.ACTION_CANCEL, -1);
entity.deleteData();
} }
@Override public void onComplete() { @Override public void onComplete() {
entity.setState(DownloadEntity.STATE_COMPLETE);
entity.setComplete(true);
entity.setSpeed(0);
sendInState2Target(DownloadSchedulers.COMPLETE);
sendIntent(Aria.ACTION_COMPLETE, entity.getFileSize());
} }
@Override public void onFail() { @Override public void onFail() {
entity.setFailNum(entity.getFailNum() + 1);
entity.setState(DownloadEntity.STATE_FAIL);
entity.setSpeed(0);
sendInState2Target(DownloadSchedulers.FAIL);
sendIntent(Aria.ACTION_FAIL, -1);
}
/**
* 将任务状态发送给下载器
*
* @param state {@link DownloadSchedulers#START}
*/
private void sendInState2Target(int state) {
if (outHandler.get() != null) {
outHandler.get().obtainMessage(state, task).sendToTarget();
} }
} }
static class Builder { private void sendIntent(String action, long location) {
entity.setComplete(action.equals(Aria.ACTION_COMPLETE));
entity.setCurrentProgress(location);
entity.update();
Intent intent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), action);
intent.putExtra(Aria.ENTITY, entity);
if (location != -1) {
intent.putExtra(Aria.CURRENT_LOCATION, location);
}
if (Configuration.isOpenBreadCast) {
AriaManager.APP.sendBroadcast(intent);
}
}
}
public static class Builder {
private Handler mOutHandler; private Handler mOutHandler;
private UploadTaskEntity mTaskEntity; private UploadTaskEntity mTaskEntity;
private String mTargetName;
public void setOutHandler(Handler outHandler){ public void setOutHandler(ISchedulers outHandler) {
mOutHandler = outHandler; mOutHandler = new Handler(outHandler);
} }
public void setUploadTaskEntity(UploadTaskEntity taskEntity){ public void setUploadTaskEntity(UploadTaskEntity taskEntity) {
mTaskEntity = taskEntity; mTaskEntity = taskEntity;
} }
public Builder(){ public void setTargetName(String targetName) {
mTargetName = targetName;
}
public Builder() {
} }
public UploadTask build(){ public UploadTask build() {
UploadTask task = new UploadTask(mTaskEntity, mOutHandler); UploadTask task = new UploadTask(mTaskEntity, mOutHandler);
task.setTargetName(mTargetName);
return task; return task;
} }
} }
} }

@ -1,25 +1,36 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.upload; package com.arialyy.aria.core.upload;
import com.arialyy.aria.core.RequestEnum; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Created by Aria.Lao on 2017/2/9. * Created by Aria.Lao on 2017/2/9.
* 上传任务实体
*/ */
public class UploadTaskEntity extends ITaskEntity {
public class UploadTaskEntity implements ITaskEntity {
public UploadEntity uploadEntity; public UploadEntity uploadEntity;
public RequestEnum requestEnum = RequestEnum.GET;
public String uploadUrl; //上传路径 public String uploadUrl; //上传路径
public String attachment; //文件上传需要的key public String attachment; //文件上传需要的key
public String contentType = "multipart/form-data"; //上传的文件类型 public String contentType = "multipart/form-data"; //上传的文件类型
public String charset = "utf-8"; public String charset = "utf-8";
/**
* http 请求头
*/
public Map<String, String> headers = new HashMap<>();
/** /**
* 文件上传表单 * 文件上传表单
*/ */
@ -28,4 +39,8 @@ public class UploadTaskEntity implements ITaskEntity {
public UploadTaskEntity(UploadEntity downloadEntity) { public UploadTaskEntity(UploadEntity downloadEntity) {
this.uploadEntity = downloadEntity; this.uploadEntity = downloadEntity;
} }
@Override public IEntity getEntity() {
return uploadEntity;
}
} }

@ -1,49 +0,0 @@
package com.arialyy.aria.core.upload;
import com.arialyy.aria.core.queue.ITaskQueue;
/**
* Created by Aria.Lao on 2017/2/23.
*/
public class UploadTaskQueue implements ITaskQueue<UploadTask, UploadTaskEntity, UploadEntity>{
@Override public void startTask(UploadTask task) {
}
@Override public void stopTask(UploadTask task) {
}
@Override public void cancelTask(UploadTask task) {
}
@Override public void reTryStart(UploadTask task) {
}
@Override public int size() {
return 0;
}
@Override public void setDownloadNum(int downloadNum) {
}
@Override public UploadTask createTask(String targetName, UploadTaskEntity entity) {
return null;
}
@Override public UploadTask getTask(UploadEntity entity) {
return null;
}
@Override public void removeTask(UploadEntity entity) {
}
@Override public UploadTask getNextTask() {
return null;
}
}

@ -32,6 +32,8 @@ public class UploadUtil implements Runnable {
private OutputStream mOutputStream; private OutputStream mOutputStream;
private HttpURLConnection mHttpConn; private HttpURLConnection mHttpConn;
private long mCurrentLocation = 0; private long mCurrentLocation = 0;
private boolean isCancel = false;
private boolean isRunning = false;
public UploadUtil(UploadTaskEntity taskEntity, IUploadListener listener) { public UploadUtil(UploadTaskEntity taskEntity, IUploadListener listener) {
mTaskEntity = taskEntity; mTaskEntity = taskEntity;
@ -44,14 +46,21 @@ public class UploadUtil implements Runnable {
} }
public void start() { public void start() {
isCancel = false;
isRunning = false;
new Thread(this).start(); new Thread(this).start();
} }
public void cancel(){
isCancel = true;
isRunning = false;
}
@Override public void run() { @Override public void run() {
File uploadFile = new File(mUploadEntity.getFilePath()); File uploadFile = new File(mUploadEntity.getFilePath());
if (!uploadFile.exists()) { if (!uploadFile.exists()) {
Log.e(TAG, "【" + mUploadEntity.getFilePath() + "】,文件不存在。"); Log.e(TAG, "【" + mUploadEntity.getFilePath() + "】,文件不存在。");
mListener.onFail(); fail();
return; return;
} }
@ -66,7 +75,7 @@ public class UploadUtil implements Runnable {
mHttpConn.setDoInput(true); mHttpConn.setDoInput(true);
mHttpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); mHttpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
mHttpConn.setRequestProperty("User-Agent", "CodeJava Agent"); mHttpConn.setRequestProperty("User-Agent", "CodeJava Agent");
mHttpConn.setRequestProperty("Range", "bytes=" + 0 + "-" + "100"); //mHttpConn.setRequestProperty("Range", "bytes=" + 0 + "-" + "100");
//内部缓冲区---分段上传防止oom //内部缓冲区---分段上传防止oom
mHttpConn.setChunkedStreamingMode(1024); mHttpConn.setChunkedStreamingMode(1024);
@ -89,9 +98,21 @@ public class UploadUtil implements Runnable {
Log.d(TAG, finish() + ""); Log.d(TAG, finish() + "");
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
e.printStackTrace(); e.printStackTrace();
fail();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
fail();
}
}
public boolean isRunning() {
return isRunning;
} }
private void fail() {
mWriter.flush();
mWriter.close();
mListener.onFail();
} }
/** /**
@ -139,13 +160,23 @@ public class UploadUtil implements Runnable {
while ((bytesRead = inputStream.read(buffer)) != -1) { while ((bytesRead = inputStream.read(buffer)) != -1) {
mCurrentLocation += bytesRead; mCurrentLocation += bytesRead;
mOutputStream.write(buffer, 0, bytesRead); mOutputStream.write(buffer, 0, bytesRead);
if (isCancel) {
break;
}
isRunning = true;
mListener.onProgress(mCurrentLocation); mListener.onProgress(mCurrentLocation);
} }
mOutputStream.flush(); mOutputStream.flush();
inputStream.close(); inputStream.close();
mListener.onComplete();
mWriter.append(LINE_END); mWriter.append(LINE_END);
mWriter.flush(); mWriter.flush();
isRunning = false;
if (isCancel) {
mListener.onCancel();
return;
}
mListener.onComplete();
} }
/** /**
@ -173,6 +204,9 @@ public class UploadUtil implements Runnable {
throw new IOException("Server returned non-OK status: " + status); throw new IOException("Server returned non-OK status: " + status);
} }
mWriter.flush();
mWriter.close();
return response.toString(); return response.toString();
} }
} }

@ -77,6 +77,13 @@ public class CheckUtil {
if (TextUtils.isEmpty(downloadUrl)) throw new IllegalArgumentException("下载链接不能为null"); if (TextUtils.isEmpty(downloadUrl)) throw new IllegalArgumentException("下载链接不能为null");
} }
/**
* 检测上传地址是否为null
*/
public static void checkUploadPath(String uploadPath) {
if (TextUtils.isEmpty(uploadPath)) throw new IllegalArgumentException("上传地址不能为null");
}
/** /**
* 检查任务实体 * 检查任务实体
*/ */

@ -21,9 +21,8 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.command.CmdFactory; import com.arialyy.aria.core.command.CmdFactory;
import com.arialyy.aria.core.command.IDownloadCmd; import com.arialyy.aria.core.command.AbsCmd;
import com.arialyy.aria.core.inf.ITaskEntity; import com.arialyy.aria.core.inf.ITaskEntity;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -41,7 +40,7 @@ import java.util.Properties;
public class CommonUtil { public class CommonUtil {
private static final String TAG = "util"; private static final String TAG = "util";
public static <T extends ITaskEntity> IDownloadCmd createDownloadCmd(String target, T entity, int cmd) { public static <T extends ITaskEntity> AbsCmd createCmd(String target, T entity, int cmd) {
return CmdFactory.getInstance().createCmd(target, entity, cmd); return CmdFactory.getInstance().createCmd(target, entity, cmd);
} }

@ -84,7 +84,7 @@ public class DownloadDialog extends AbsDialog {
mStop.setEnabled(!startEnable); mStop.setEnabled(!startEnable);
} }
private class MyDialogDownloadCallback extends Aria.SimpleSchedulerListener { private class MyDialogDownloadCallback extends Aria.DownloadSchedulerListener {
@Override public void onTaskPre(DownloadTask task) { @Override public void onTaskPre(DownloadTask task) {
super.onTaskPre(task); super.onTaskPre(task);

@ -88,7 +88,7 @@ public class DownloadFragment extends AbsFragment<FragmentDownloadBinding> {
mStop.setEnabled(!startEnable); mStop.setEnabled(!startEnable);
} }
private class MyDialogDownloadCallback extends Aria.SimpleSchedulerListener { private class MyDialogDownloadCallback extends Aria.DownloadSchedulerListener {
@Override public void onTaskPre(DownloadTask task) { @Override public void onTaskPre(DownloadTask task) {
super.onTaskPre(task); super.onTaskPre(task);

@ -25,7 +25,7 @@ public class DownloadActivity extends BaseActivity<ActivityDownloadBinding> {
@Override protected void init(Bundle savedInstanceState) { @Override protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState); super.init(savedInstanceState);
mAdapter = new DownloadAdapter(this, Aria.download(this).getDownloadList()); mAdapter = new DownloadAdapter(this, Aria.download(this).getTaskList());
mList.setLayoutManager(new LinearLayoutManager(this)); mList.setLayoutManager(new LinearLayoutManager(this));
mList.setAdapter(mAdapter); mList.setAdapter(mAdapter);
} }
@ -39,7 +39,7 @@ public class DownloadActivity extends BaseActivity<ActivityDownloadBinding> {
Aria.download(this).addSchedulerListener(new MySchedulerListener()); Aria.download(this).addSchedulerListener(new MySchedulerListener());
} }
private class MySchedulerListener extends Aria.SimpleSchedulerListener { private class MySchedulerListener extends Aria.DownloadSchedulerListener {
@Override public void onTaskPre(DownloadTask task) { @Override public void onTaskPre(DownloadTask task) {
super.onTaskPre(task); super.onTaskPre(task);
L.d(TAG, "download pre"); L.d(TAG, "download pre");

@ -87,7 +87,7 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
} }
} }
private class DownloadListener extends Aria.SimpleSchedulerListener { private class DownloadListener extends Aria.DownloadSchedulerListener {
@Override public void onTaskStart(DownloadTask task) { @Override public void onTaskStart(DownloadTask task) {
super.onTaskStart(task); super.onTaskStart(task);

@ -50,7 +50,7 @@ public class SimpleNotification {
Aria.download(mContext).load(DOWNLOAD_URL).stop(); Aria.download(mContext).load(DOWNLOAD_URL).stop();
} }
private static class DownloadCallback extends Aria.SimpleSchedulerListener { private static class DownloadCallback extends Aria.DownloadSchedulerListener {
NotificationCompat.Builder mBuilder; NotificationCompat.Builder mBuilder;
NotificationManager mManager; NotificationManager mManager;

@ -86,7 +86,7 @@ public class DownloadPopupWindow extends AbsPopupWindow {
mStop.setEnabled(!startEnable); mStop.setEnabled(!startEnable);
} }
private class MyDialogDownloadCallback extends Aria.SimpleSchedulerListener { private class MyDialogDownloadCallback extends Aria.DownloadSchedulerListener {
@Override public void onTaskPre(DownloadTask task) { @Override public void onTaskPre(DownloadTask task) {
super.onTaskPre(task); super.onTaskPre(task);

@ -207,7 +207,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
Aria.download(this).load(DOWNLOAD_URL).cancel(); Aria.download(this).load(DOWNLOAD_URL).cancel();
} }
private class MySchedulerListener extends Aria.SimpleSchedulerListener { private class MySchedulerListener extends Aria.DownloadSchedulerListener {
@Override public void onTaskStart(DownloadTask task) { @Override public void onTaskStart(DownloadTask task) {
mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize()) mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize())
.sendToTarget(); .sendToTarget();

@ -8,15 +8,6 @@
> >
<include layout="@layout/layout_bar"/> <include layout="@layout/layout_bar"/>
<Button
android:id="@+id/single_task"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="上传"
style="?buttonBarButtonStyle"
/>
<com.arialyy.simple.widget.HorizontalProgressBarWithNumber <com.arialyy.simple.widget.HorizontalProgressBarWithNumber
android:id="@+id/pb" android:id="@+id/pb"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -26,6 +17,15 @@
style="?android:attr/progressBarStyleHorizontal" style="?android:attr/progressBarStyleHorizontal"
/> />
<Button
android:id="@+id/single_task"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="上传"
style="?buttonBarButtonStyle"
/>
</LinearLayout> </LinearLayout>
</layout> </layout>

Loading…
Cancel
Save