pull/330/head
laoyuyu 7 years ago
commit cf65959bf9
  1. 2
      Aria/build.gradle
  2. 9
      Aria/src/main/java/com/arialyy/aria/core/ConfigHelper.java
  3. 2
      Aria/src/main/java/com/arialyy/aria/core/command/group/GroupCancelCmd.java
  4. 19
      Aria/src/main/java/com/arialyy/aria/core/command/normal/AbsNormalCmd.java
  5. 72
      Aria/src/main/java/com/arialyy/aria/core/command/normal/CancelAllCmd.java
  6. 88
      Aria/src/main/java/com/arialyy/aria/core/command/normal/ResumeAllCmd.java
  7. 6
      Aria/src/main/java/com/arialyy/aria/core/command/normal/StartCmd.java
  8. 88
      Aria/src/main/java/com/arialyy/aria/core/common/AbsFileer.java
  9. 56
      Aria/src/main/java/com/arialyy/aria/core/common/AbsFtpInfoThread.java
  10. 4
      Aria/src/main/java/com/arialyy/aria/core/common/AbsFtpThreadTask.java
  11. 166
      Aria/src/main/java/com/arialyy/aria/core/common/AbsThreadTask.java
  12. 22
      Aria/src/main/java/com/arialyy/aria/core/common/ProxyHelper.java
  13. 5
      Aria/src/main/java/com/arialyy/aria/core/common/StateConstance.java
  14. 6
      Aria/src/main/java/com/arialyy/aria/core/common/TaskRecord.java
  15. 16
      Aria/src/main/java/com/arialyy/aria/core/download/BaseDListener.java
  16. 5
      Aria/src/main/java/com/arialyy/aria/core/download/BaseGroupTarget.java
  17. 6
      Aria/src/main/java/com/arialyy/aria/core/download/BaseNormalTarget.java
  18. 8
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadGroupListener.java
  19. 7
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadGroupTarget.java
  20. 46
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadReceiver.java
  21. 21
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTarget.java
  22. 7
      Aria/src/main/java/com/arialyy/aria/core/download/FtpDirDownloadTarget.java
  23. 8
      Aria/src/main/java/com/arialyy/aria/core/download/FtpDownloadTarget.java
  24. 89
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/AbsGroupUtil.java
  25. 20
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/ConnectionHelp.java
  26. 56
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/DownloadGroupUtil.java
  27. 13
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/Downloader.java
  28. 160
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/FtpThreadTask.java
  29. 11
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/HttpFileInfoThread.java
  30. 118
      Aria/src/main/java/com/arialyy/aria/core/download/downloader/HttpThreadTask.java
  31. 3
      Aria/src/main/java/com/arialyy/aria/core/inf/AbsEntity.java
  32. 7
      Aria/src/main/java/com/arialyy/aria/core/inf/AbsTarget.java
  33. 11
      Aria/src/main/java/com/arialyy/aria/core/inf/AbsTaskEntity.java
  34. 5
      Aria/src/main/java/com/arialyy/aria/core/inf/IFtpTarget.java
  35. 4
      Aria/src/main/java/com/arialyy/aria/core/inf/IHttpHeaderTarget.java
  36. 7
      Aria/src/main/java/com/arialyy/aria/core/manager/DGTEFactory.java
  37. 7
      Aria/src/main/java/com/arialyy/aria/core/manager/TEManager.java
  38. 26
      Aria/src/main/java/com/arialyy/aria/core/queue/AbsTaskQueue.java
  39. 5
      Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java
  40. 9
      Aria/src/main/java/com/arialyy/aria/core/scheduler/AbsSchedulers.java
  41. 2
      Aria/src/main/java/com/arialyy/aria/core/upload/BaseNormalTarget.java
  42. 9
      Aria/src/main/java/com/arialyy/aria/core/upload/BaseUListener.java
  43. 2
      Aria/src/main/java/com/arialyy/aria/core/upload/FtpUploadTarget.java
  44. 13
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadReceiver.java
  45. 7
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTarget.java
  46. 34
      Aria/src/main/java/com/arialyy/aria/core/upload/uploader/FtpThreadTask.java
  47. 6
      Aria/src/main/java/com/arialyy/aria/core/upload/uploader/HttpThreadTask.java
  48. 2
      Aria/src/main/java/com/arialyy/aria/orm/AbsDelegate.java
  49. 5
      Aria/src/main/java/com/arialyy/aria/orm/DelegateFind.java
  50. 3
      Aria/src/main/java/com/arialyy/aria/util/ALog.java
  51. 206
      Aria/src/main/java/com/arialyy/aria/util/CommonUtil.java
  52. 9
      Aria/src/main/java/com/arialyy/aria/util/Regular.java
  53. 9
      DEV_LOG.md
  54. 22
      README.md
  55. 9
      app/src/main/AndroidManifest.xml
  56. 18
      app/src/main/assets/aria_config.xml
  57. 11
      app/src/main/java/com/arialyy/simple/download/FtpDownloadActivity.java
  58. 9
      app/src/main/java/com/arialyy/simple/download/SingleTaskActivity.java
  59. 5
      app/src/main/java/com/arialyy/simple/download/group/DownloadGroupActivity.java
  60. 2
      app/src/main/java/com/arialyy/simple/download/group/GroupModule.java
  61. 4
      app/src/main/java/com/arialyy/simple/download/multi_download/DownloadAdapter.java
  62. 6
      app/src/main/java/com/arialyy/simple/download/multi_download/MultiDownloadActivity.java
  63. 2
      app/src/main/java/com/arialyy/simple/download/multi_download/MultiTaskActivity.java
  64. 16
      app/src/main/java/com/arialyy/simple/test/AnyRunActivity.java
  65. 6
      app/src/main/java/com/arialyy/simple/test/AnyRunnModule.java
  66. 8
      app/src/main/java/com/arialyy/simple/test/TestActivity.java
  67. 9
      app/src/main/res/values/strings.xml
  68. 1
      aria/src/main/AndroidManifest.xml
  69. 25
      aria/src/main/java/com/arialyy/aria/core/Configuration.java
  70. 2
      build.gradle

@ -28,6 +28,6 @@ dependencies {
compile project(':AriaAnnotations')
compile 'com.arialyy.aria:aria-ftp-plug:1.0.3'
// compile project(':AriaFtpPlug')
// compile project(':AriaFtpPlug')
}
apply from: 'bintray-release.gradle'

@ -59,9 +59,6 @@ class ConfigHelper extends DefaultHandler {
String value = attributes.getValue("value");
switch (qName) {
case "openDynamicFile":
loadOpenDynamicFile(value);
break;
case "threadNum":
loadThreadNum(value);
break;
@ -117,12 +114,6 @@ class ConfigHelper extends DefaultHandler {
}
}
private void loadOpenDynamicFile(String value) {
if (isDownloadConfig) {
mDownloadConfig.openDynamicFile = checkBoolean(value) ? Boolean.valueOf(value) : false;
}
}
private void loadNotNetRetry(String value) {
if (isDownloadConfig) {
mDownloadConfig.notNetRetry = checkBoolean(value) ? Boolean.valueOf(value) : false;

@ -19,7 +19,7 @@ import com.arialyy.aria.core.inf.AbsGroupTaskEntity;
/**
* Created by AriaL on 2017/6/29.
* 删除任务组
* 删除任务组子任务
*/
class GroupCancelCmd<T extends AbsGroupTaskEntity> extends AbsGroupCmd<T> {
/**

@ -90,10 +90,12 @@ public abstract class AbsNormalCmd<T extends AbsTaskEntity> extends AbsCmd<T> {
}
/**
* 删除所有任务
* 发送等待状态
*/
void removeAll() {
mQueue.removeAllTask();
void sendWaitState(AbsTask task) {
if (task != null) {
task.getOutHandler().obtainMessage(ISchedulers.WAIT, task).sendToTarget();
}
}
/**
@ -119,6 +121,17 @@ public abstract class AbsNormalCmd<T extends AbsTaskEntity> extends AbsCmd<T> {
mQueue.cancelTask(tempTask);
}
/**
* 删除任务
*/
void removeTask(AbsTaskEntity taskEntity) {
AbsTask tempTask = getTask(taskEntity.getEntity());
if (tempTask == null){
tempTask = createTask(taskEntity);
}
mQueue.cancelTask(tempTask);
}
/**
* 启动任务
*/

@ -16,7 +16,19 @@
package com.arialyy.aria.core.command.normal;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadGroupEntity;
import com.arialyy.aria.core.download.DownloadGroupTaskEntity;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.core.manager.TEManager;
import com.arialyy.aria.core.queue.DownloadGroupTaskQueue;
import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTaskEntity;
import com.arialyy.aria.orm.DbEntity;
import java.util.List;
/**
* Created by AriaL on 2017/6/27.
@ -37,6 +49,64 @@ public class CancelAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
}
@Override public void executeCmd() {
removeAll();
if (!canExeCmd) return;
if (isDownloadCmd) {
removeAllDTask();
removeAllDGTask();
} else {
removeUTask();
}
}
/**
* 删除所有普通下载任务
*/
private void removeAllDTask() {
List<DownloadEntity> entities =
DbEntity.findDatas(DownloadEntity.class, "isGroupChild=?", "false");
if (entities != null && !entities.isEmpty()) {
for (DownloadEntity entity : entities) {
remove(TEManager.getInstance().getTEntity(DownloadTaskEntity.class, entity.getKey()));
}
}
}
/**
* 删除所有下载任务组任务
*/
private void removeAllDGTask() {
List<DownloadGroupEntity> entities =
DbEntity.findDatas(DownloadGroupEntity.class, "state!=?", "-1");
if (entities != null && !entities.isEmpty()) {
for (DownloadGroupEntity entity : entities) {
remove(
TEManager.getInstance().getGTEntity(DownloadGroupTaskEntity.class, entity.getUrls()));
}
}
}
/**
* 删除所有普通上传任务
*/
private void removeUTask() {
List<UploadEntity> entities =
DbEntity.findDatas(UploadEntity.class, "isGroupChild=?", "false");
if (entities != null && !entities.isEmpty()) {
for (UploadEntity entity : entities) {
remove(TEManager.getInstance().getTEntity(UploadTaskEntity.class, entity.getKey()));
}
}
}
private void remove(AbsTaskEntity te) {
if (te instanceof DownloadTaskEntity) {
mQueue = DownloadTaskQueue.getInstance();
} else if (te instanceof UploadTaskEntity) {
mQueue = UploadTaskQueue.getInstance();
} else if (te instanceof DownloadGroupTaskEntity) {
mQueue = DownloadGroupTaskQueue.getInstance();
}
te.setRemoveFile(removeFile);
removeTask(te);
}
}

@ -1,17 +1,19 @@
package com.arialyy.aria.core.command.normal;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadGroupEntity;
import com.arialyy.aria.core.download.DownloadGroupTaskEntity;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.download.wrapper.DGTEWrapper;
import com.arialyy.aria.core.download.wrapper.DTEWrapper;
import com.arialyy.aria.core.inf.AbsTask;
import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.manager.TEManager;
import com.arialyy.aria.core.queue.DownloadGroupTaskQueue;
import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTaskEntity;
import com.arialyy.aria.core.upload.wrapper.UTEWrapper;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
@ -42,10 +44,10 @@ final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
return;
}
if (isDownloadCmd) {
resumeTask(findTaskData(1));
resumeTask(findTaskData(2));
findTaskData(1);
findTaskData(2);
} else {
resumeTask(findTaskData(3));
findTaskData(3);
}
resumeWaitTask();
}
@ -55,54 +57,49 @@ final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
*
* @param type {@code 1}单任务下载任务{@code 2}任务组下载任务{@code 3} 单任务上传任务
*/
private List<AbsTaskEntity> findTaskData(int type) {
// TODO: 2018/4/20 需要测试
List<AbsTaskEntity> tempList = new ArrayList<>();
private void findTaskData(int type) {
if (type == 1) {
List<DTEWrapper> wrappers = DbEntity.findRelationData(DTEWrapper.class,
"DownloadTaskEntity.isGroupTask=? and DownloadTaskEntity.state!=?", "false", "1");
if (wrappers != null && !wrappers.isEmpty()) {
for (DTEWrapper w : wrappers) {
tempList.add(w.taskEntity);
List<DownloadEntity> entities =
DbEntity.findDatas(DownloadEntity.class,
"isGroupChild=? and state!=?", "false", "1");
if (entities != null && !entities.isEmpty()) {
for (DownloadEntity entity : entities) {
resumeTask(TEManager.getInstance().getTEntity(DownloadTaskEntity.class, entity.getKey()));
}
}
} else if (type == 2) {
List<DGTEWrapper> wrappers =
DbEntity.findRelationData(DGTEWrapper.class, "DownloadGroupTaskEntity.state!=?", "1");
if (wrappers != null && !wrappers.isEmpty()) {
for (DGTEWrapper w : wrappers) {
tempList.add(w.taskEntity);
List<DownloadGroupEntity> entities =
DbEntity.findDatas(DownloadGroupEntity.class, "state!=?", "1");
if (entities != null && !entities.isEmpty()) {
for (DownloadGroupEntity entity : entities) {
resumeTask(
TEManager.getInstance().getGTEntity(DownloadGroupTaskEntity.class, entity.getUrls()));
}
}
} else if (type == 3) {
List<UTEWrapper> wrappers =
DbEntity.findRelationData(UTEWrapper.class, "UploadTaskEntity.state!=?", "1");
if (wrappers != null && !wrappers.isEmpty()) {
for (UTEWrapper w : wrappers) {
tempList.add(w.taskEntity);
List<UploadEntity> entities =
DbEntity.findDatas(UploadEntity.class, "state!=?", "1");
if (entities != null && !entities.isEmpty()) {
for (UploadEntity entity : entities) {
resumeTask(TEManager.getInstance().getTEntity(UploadTaskEntity.class, entity.getKey()));
}
}
}
return tempList;
}
/**
* 恢复任务
*/
private void resumeTask(List<AbsTaskEntity> taskList) {
if (taskList != null && !taskList.isEmpty()) {
for (AbsTaskEntity te : taskList) {
if (te == null || te.getEntity() == null) continue;
int state = te.getState();
if (state == IEntity.STATE_STOP || state == IEntity.STATE_OTHER) {
resumeEntity(te);
} else if (state == IEntity.STATE_WAIT) {
mWaitList.add(te);
} else if (state == IEntity.STATE_RUNNING) {
if (!mQueue.taskIsRunning(te.getEntity().getKey())) {
resumeEntity(te);
}
}
private void resumeTask(AbsTaskEntity te) {
if (te == null || te.getEntity() == null) return;
int state = te.getState();
if (state == IEntity.STATE_STOP || state == IEntity.STATE_OTHER) {
resumeEntity(te);
} else if (state == IEntity.STATE_WAIT) {
mWaitList.add(te);
} else if (state == IEntity.STATE_RUNNING) {
if (!mQueue.taskIsRunning(te.getEntity().getKey())) {
resumeEntity(te);
}
}
}
@ -117,6 +114,13 @@ final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
if (mQueue.getCurrentExePoolNum() < maxTaskNum) {
startTask(createTask(te));
} else {
if (te instanceof DownloadTaskEntity) {
mQueue = DownloadTaskQueue.getInstance();
} else if (te instanceof UploadTaskEntity) {
mQueue = UploadTaskQueue.getInstance();
} else if (te instanceof DownloadGroupTaskEntity) {
mQueue = DownloadGroupTaskQueue.getInstance();
}
createTask(te);
}
}
@ -129,7 +133,8 @@ final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
*/
private void resumeEntity(AbsTaskEntity te) {
if (te instanceof DownloadTaskEntity) {
if (te.getRequestType() == AbsTaskEntity.D_FTP || te.getRequestType() == AbsTaskEntity.U_FTP) {
if (te.getRequestType() == AbsTaskEntity.D_FTP
|| te.getRequestType() == AbsTaskEntity.U_FTP) {
te.setUrlEntity(CommonUtil.getFtpUrlInfo(te.getEntity().getKey()));
}
mQueue = DownloadTaskQueue.getInstance();
@ -143,7 +148,8 @@ final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
startTask(createTask(te));
} else {
te.getEntity().setState(IEntity.STATE_WAIT);
createTask(te);
AbsTask task = createTask(te);
sendWaitState(task);
}
}
}

@ -86,8 +86,11 @@ class StartCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
}
}
} else {
if (!task.isRunning()) {
//任务没执行并且执行队列中没有该任务,才认为任务没有运行中
if (!task.isRunning() && !mQueue.taskIsRunning(task.getKey())) {
resumeTask();
}else {
ALog.w(TAG, String.format("任务【%s】已经在运行", task.getTaskName()));
}
}
if (mQueue.getCurrentCachePoolNum() == 0) {
@ -114,7 +117,6 @@ class StartCmd<T extends AbsTaskEntity> extends AbsNormalCmd<T> {
}
private List<AbsTaskEntity> findWaitData(int type) {
// TODO: 2018/4/20 需要测试
List<AbsTaskEntity> waitList = new ArrayList<>();
if (type == 1) {
List<DTEWrapper> wrappers = DbEntity.findRelationData(DTEWrapper.class,

@ -16,7 +16,6 @@
package com.arialyy.aria.core.common;
import android.content.Context;
import android.util.SparseArray;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.AbsNormalEntity;
@ -29,8 +28,10 @@ import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.DbHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Timer;
@ -44,8 +45,11 @@ import java.util.concurrent.Executors;
*/
public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY extends AbsTaskEntity<ENTITY>>
implements Runnable, IUtil {
public static final String STATE = "_state_";
public static final String RECORD = "_record_";
private static final String STATE = "_state_";
private static final String RECORD = "_record_";
/**
* 小于1m的文件不启用多线程
*/
protected static final long SUB_LEN = 1024 * 1024;
private final String TAG = "AbsFileer";
@ -57,24 +61,20 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
protected StateConstance mConstance;
private ExecutorService mFixedThreadPool;
//总线程数
private int mTotalThreadNum;
protected int mTotalThreadNum;
//启动线程数
private int mStartThreadNum;
//已完成的线程数
private int mCompleteThreadNum;
private SparseArray<AbsThreadTask> mTask = new SparseArray<>();
private Map<Integer, AbsThreadTask> mTask = new HashMap<>();
/**
* 小于1m的文件不启用多线程
*/
private Timer mTimer;
@Deprecated
private File mConfigFile;
@Deprecated private File mConfigFile;
/**
* 进度刷新间隔
*/
private long mUpdateInterval = 1000;
protected TaskRecord mRecord;
private TaskRecord mRecord;
protected AbsFileer(IEventListener listener, TASK_ENTITY taskEntity) {
mListener = listener;
@ -124,6 +124,16 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
handleBreakpoint();
}
mConstance.START_THREAD_NUM = mTotalThreadNum;
/*
* mTaskEntity.getEntity().getFileSize() != mTempFile.length()为兼容以前老版本代码
* 动态长度条件
* 1总线程数为1并且是新任务
* 2总线程数为1不是新任务但是长度不是文件全长度
*/
if (mTotalThreadNum == 1 && (mTaskEntity.isNewTask()
|| mTaskEntity.getEntity().getFileSize() != mTempFile.length())) {
mConstance.isOpenDynamicFile = true;
}
startTimer();
}
@ -177,7 +187,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
}
/**
* 获取当前下载位置
* 获取当前任务位置
*/
@Override public long getCurrentLocation() {
return mConstance.CURRENT_LOCATION;
@ -233,11 +243,11 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
* 检查任务检查线程数
* 新任务条件
* 1文件不存在
* 2下载记录文件缺失或不匹配
* 2任务记录文件缺失或不匹配
* 3数据库记录不存在
* 4不支持断点则是新任务
*/
protected void checkTask() {
private void checkTask() {
mConfigFile = new File(CommonUtil.getFileConfigPath(false, mEntity.getFileName()));
if (mConfigFile.exists()) {
convertDb();
@ -307,14 +317,14 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
tRecord.key = mRecord.filePath;
Object state = pro.getProperty(mTempFile.getName() + STATE + i);
Object record = pro.getProperty(mTempFile.getName() + RECORD + i);
if (state != null && Integer.parseInt(state + "") == 1) {
if (state != null && Integer.parseInt(String.valueOf(state)) == 1) {
mCompleteThreadNum++;
tRecord.isComplete = true;
continue;
}
mStartThreadNum++;
if (record != null) {
Long temp = Long.parseLong(record + "");
Long temp = Long.parseLong(String.valueOf(record));
tRecord.startLocation = temp > 0 ? temp : 0;
} else {
tRecord.startLocation = 0;
@ -334,8 +344,6 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
mRecord.filePath = mTaskEntity.getKey();
mRecord.threadRecords = new ArrayList<>();
mRecord.isGroupRecord = mTaskEntity.getEntity().isGroupChild();
mRecord.isOpenDynamicFile =
AriaManager.getInstance(AriaManager.APP).getDownloadConfig().isOpenDynamicFile();
if (mRecord.isGroupRecord) {
if (mTaskEntity.getEntity() instanceof DownloadEntity) {
mRecord.dGroupName = ((DownloadEntity) mTaskEntity.getEntity()).getGroupName();
@ -347,6 +355,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
* 保存任务记录
*/
private void saveRecord() {
mRecord.threadNum = mRecord.threadRecords.size();
mRecord.save();
for (ThreadRecord tr : mRecord.threadRecords) {
tr.save();
@ -364,7 +373,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
*/
private boolean resumeRecordLocation(int i, long startL, long endL) {
mConstance.CURRENT_LOCATION += endL - startL;
ALog.d(TAG, "任务【" + mTaskEntity.getEntity().getFileName() + "】线程__" + i + "__已完成");
ALog.d(TAG, String.format("任务【%s】线程__%s__已完成", mTaskEntity.getEntity().getFileName(), i));
mConstance.COMPLETE_THREAD_NUM = mCompleteThreadNum;
mConstance.STOP_NUM++;
mConstance.CANCEL_NUM++;
@ -430,7 +439,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
continue;
}
//如果有记录,则恢复下载
//如果有记录,则恢复任务
if (tr.startLocation >= 0) {
Long r = tr.startLocation;
//记录的位置需要在线程区间中
@ -438,7 +447,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
mConstance.CURRENT_LOCATION += r - startL;
startL = r;
}
ALog.d(TAG, "任务【" + mEntity.getFileName() + "】线程__" + i + "__恢复下载");
ALog.d(TAG, String.format("任务【%s】线程__%s__恢复任务", mEntity.getFileName(), i));
}
//最后一个线程的结束位置即为文件的总长度
if (i == (mTotalThreadNum - 1)) {
@ -456,12 +465,17 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
threadId[rl] = i;
rl++;
}
if (mConstance.CURRENT_LOCATION != 0
&& mConstance.CURRENT_LOCATION != mEntity.getCurrentProgress()) {
ALog.d(TAG, "进度修正");
mEntity.setCurrentProgress(mConstance.CURRENT_LOCATION);
}
saveRecord();
startThreadTask(threadId);
}
/**
* 启动单线程下载任务
* 启动单线程任务
*/
private void startThreadTask(int[] recordL) {
if (mConstance.CURRENT_LOCATION > 0) {
@ -479,6 +493,34 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
}
}
/**
* 重试线程任务只有线程创建成功才能重试
*/
public void retryThreadTask() {
if (mTask == null || mTask.size() == 0) {
ALog.w(TAG, "没有线程任务");
return;
}
Set<Integer> keys = mTask.keySet();
for (Integer key : keys) {
AbsThreadTask task = mTask.get(key);
if (task != null && !task.isThreadComplete()) {
task.getConfig().START_LOCATION = task.getCurrentLocation();
mConstance.isStop = false;
mConstance.isCancel = false;
mConstance.isRunning = true;
ALog.d(TAG, String.format("任务【%s】开始重试,线程__%s__【开始位置:%s,结束位置:%s】", mEntity.getFileName(),
key, task.getConfig().START_LOCATION, task.getConfig().END_LOCATION));
if (!mFixedThreadPool.isShutdown()) {
mFixedThreadPool.execute(task);
} else {
ALog.w(TAG, "线程池已关闭");
mListener.onFail(true);
}
}
}
}
/**
* 处理新任务
*
@ -487,7 +529,7 @@ public abstract class AbsFileer<ENTITY extends AbsNormalEntity, TASK_ENTITY exte
protected abstract boolean handleNewTask();
/**
* 处理不支持断点的下载
* 处理不支持断点的任务
*/
private void handleNoSupportBP() {
SubThreadConfig<TASK_ENTITY> config = new SubThreadConfig<>();

@ -26,6 +26,7 @@ import com.arialyy.aria.util.Regular;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.net.ftp.FTP;
@ -72,7 +73,7 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
try {
client = createFtpClient();
if (client == null) {
failDownload("创建FTP客户端失败", true);
ALog.e(TAG, String.format("任务【%s】失败", mTaskEntity.getUrlEntity().url));
return;
}
String remotePath =
@ -82,8 +83,8 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
ALog.i(TAG, s);
boolean isExist = files.length != 0;
if (!isExist && !isUpload) {
failDownload("文件不存在,任务链接【" + mTaskEntity.getUrlEntity().url + "】,remotePath:" + remotePath,
false);
failDownload(String.format("文件不存在,任务链接【%s】,remotePath:%s", mTaskEntity.getUrlEntity().url,
remotePath), false);
int i = remotePath.lastIndexOf(File.separator);
FTPFile[] files1;
if (i == -1) {
@ -92,7 +93,8 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
files1 = client.listFiles(remotePath.substring(0, i + 1));
}
if (files1.length > 0) {
ALog.i(TAG, "路径【" + setRemotePath() + "】下的文件列表 ===================================");
ALog.i(TAG,
String.format("路径【%s】下的文件列表 ===================================", setRemotePath()));
for (FTPFile file : files1) {
ALog.d(TAG, file.toString());
}
@ -114,7 +116,8 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
mTaskEntity.setNewTask(true);
} else {
client.disconnect();
failDownload("获取文件信息错误,错误码为:" + reply + ",msg:" + client.getReplyString(), true);
failDownload(String.format("获取文件信息错误,错误码为:%s,msg:%s", reply, client.getReplyString()),
true);
return;
}
}
@ -171,11 +174,14 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
if (m.find() && m.groupCount() > 0) {
client = new FTPClient();
InetAddress ip = InetAddress.getByName(urlEntity.hostName);
client.setConnectTimeout(10000); // 连接10s超时
client.setConnectTimeout(mConnectTimeOut); // 连接10s超时
client.connect(ip, Integer.parseInt(urlEntity.port));
mTaskEntity.getUrlEntity().validAddr = ip;
} else {
InetAddress[] ips = InetAddress.getAllByName(urlEntity.hostName);
DNSQueryThread dnsThread = new DNSQueryThread(urlEntity.hostName);
dnsThread.start();
dnsThread.join(mConnectTimeOut);
InetAddress[] ips = dnsThread.getIps();
client = connect(new FTPClient(), ips, 0, Integer.parseInt(urlEntity.port));
}
@ -206,7 +212,8 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
failDownload("无法连接到ftp服务器,错误码为:" + reply + ",msg:" + client.getReplyString(), true);
failDownload(String.format("无法连接到ftp服务器,错误码为:%s,msg:%s", reply, client.getReplyString()),
true);
return null;
}
// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码
@ -221,9 +228,10 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
client.setDataTimeout(10 * 1000);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setConnectTimeout(mConnectTimeOut);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return client;
}
@ -232,7 +240,12 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
* 连接到ftp服务器
*/
private FTPClient connect(FTPClient client, InetAddress[] ips, int index, int port) {
if (ips == null || ips.length == 0) {
ALog.w(TAG, "无可用ip");
return null;
}
try {
client.setConnectTimeout(mConnectTimeOut); //需要先设置超时,这样才不会出现阻塞
client.connect(ips[index], port);
mTaskEntity.getUrlEntity().validAddr = ips[index];
return client;
@ -295,4 +308,29 @@ public abstract class AbsFtpInfoThread<ENTITY extends AbsEntity, TASK_ENTITY ext
mCallback.onFail(mEntity.getKey(), errorMsg, needRetry);
}
}
/**
* 获取可用IP的超时线程InetAddress.getByName没有超时功能需要自己处理超时
*/
private static class DNSQueryThread extends Thread {
private String hostName;
private InetAddress[] ips;
DNSQueryThread(String hostName) {
this.hostName = hostName;
}
@Override public void run() {
try {
ips = InetAddress.getAllByName(hostName);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
synchronized InetAddress[] getIps() {
return ips;
}
}
}

@ -87,8 +87,8 @@ public abstract class AbsFtpThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTI
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
fail(STATE.CURRENT_LOCATION,
"无法连接到ftp服务器,错误码为:" + reply + ",msg:" + client.getReplyString(), null);
fail(mChildCurrentLocation,
String.format("无法连接到ftp服务器,错误码为:%s,msg:%s", reply, client.getReplyString()), null);
return null;
}
// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码

@ -24,7 +24,6 @@ import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.ErrorHelp;
import com.arialyy.aria.util.NetUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;
@ -53,23 +52,19 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
protected SubThreadConfig<TASK_ENTITY> mConfig;
protected ENTITY mEntity;
protected TASK_ENTITY mTaskEntity;
private int mFailNum = 0;
private String mTaskType;
private int mFailTimes = 0;
private Timer mFailTimer;
private long mLastSaveTime;
private ExecutorService mConfigThreadPool;
protected int mConnectTimeOut; //连接超时时间
protected int mReadTimeOut; //流读取的超时时间
protected boolean isNotNetRetry = false; //断网情况是否重试
private boolean taskBreak = false; //任务中断
private Thread mConfigThread = new Thread(new Runnable() {
@Override public void run() {
final long currentTemp = mChildCurrentLocation;
try {
writeConfig(false, currentTemp);
} catch (IOException e) {
e.printStackTrace();
}
writeConfig(false, currentTemp);
}
});
@ -80,13 +75,10 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
mConfig = info;
mTaskEntity = mConfig.TASK_ENTITY;
mEntity = mTaskEntity.getEntity();
mTaskType = getTaskType();
mLastSaveTime = System.currentTimeMillis();
mConfigThreadPool = Executors.newCachedThreadPool();
}
protected abstract String getTaskType();
public void setMaxSpeed(double maxSpeed) {
if (-0.9999 < maxSpeed && maxSpeed < 0.00001) {
mSleepTime = 0;
@ -97,6 +89,28 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
}
}
/**
* 当前线程是否完成对于不支持断点的任务一律未完成
* {@code true} 完成{@code false} 未完成
*/
public boolean isThreadComplete() {
return mConfig.THREAD_RECORD.isComplete;
}
/**
* 获取线程配置信息
*/
public SubThreadConfig getConfig() {
return mConfig;
}
/**
* 当前线程下载进度
*/
public long getCurrentLocation() {
return mChildCurrentLocation;
}
private boolean filterVersion() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
@ -108,35 +122,38 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
}
}
/**
* 任务是否中断中断条件
* 1任务取消
* 2任务停止
* 3手动中断 {@link #taskBreak}
*
* @return {@code true} 中断{@code false} 不是中断
*/
protected boolean isBreak() {
return STATE.isCancel || STATE.isStop || taskBreak;
}
/**
* 停止任务
*/
public void stop() {
synchronized (AriaManager.LOCK) {
try {
if (mConfig.SUPPORT_BP) {
final long currentTemp = mChildCurrentLocation;
STATE.STOP_NUM++;
ALog.d(TAG, "任务【"
+ mConfig.TEMP_FILE.getName()
+ "】thread__"
+ mConfig.THREAD_ID
+ "__停止【停止位置: "
+ currentTemp
+ "】");
writeConfig(false, currentTemp);
if (STATE.isStop()) {
ALog.i(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】已停止");
STATE.isRunning = false;
mListener.onStop(STATE.CURRENT_LOCATION);
}
} else {
ALog.i(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】已停止");
if (mConfig.SUPPORT_BP) {
final long currentTemp = mChildCurrentLocation;
STATE.STOP_NUM++;
ALog.d(TAG, String.format("任务【%s】thread__%s__停止【停止位置:%s】", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID, currentTemp));
writeConfig(false, currentTemp);
if (STATE.isStop()) {
ALog.i(TAG, String.format("任务【%s】已停止", mConfig.TEMP_FILE.getName()));
STATE.isRunning = false;
mListener.onStop(STATE.CURRENT_LOCATION);
}
} catch (IOException e) {
e.printStackTrace();
} else {
ALog.i(TAG, String.format("任务【%s】已停止", mConfig.TEMP_FILE.getName()));
STATE.isRunning = false;
mListener.onStop(STATE.CURRENT_LOCATION);
}
}
}
@ -146,6 +163,11 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
*/
protected void progress(long len) {
synchronized (AriaManager.LOCK) {
if (STATE.CURRENT_LOCATION > mEntity.getFileSize()) {
taskBreak = true;
fail(mChildCurrentLocation, "下载失败,下载长度超出文件大小", null, false);
return;
}
mChildCurrentLocation += len;
STATE.CURRENT_LOCATION += len;
if (System.currentTimeMillis() - mLastSaveTime > 5000
@ -165,44 +187,54 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
synchronized (AriaManager.LOCK) {
if (mConfig.SUPPORT_BP) {
STATE.CANCEL_NUM++;
ALog.d(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】thread__" + mConfig.THREAD_ID + "__取消");
ALog.d(TAG,
String.format("任务【%s】thread__%s__取消", mConfig.TEMP_FILE.getName(), mConfig.THREAD_ID));
if (STATE.isCancel()) {
if (mConfig.TEMP_FILE.exists() && !(mEntity instanceof UploadEntity)) {
mConfig.TEMP_FILE.delete();
}
ALog.d(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】已取消");
ALog.d(TAG, String.format("任务【%s】已取消", mConfig.TEMP_FILE.getName()));
STATE.isRunning = false;
mListener.onCancel();
}
} else {
ALog.d(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】已取消");
ALog.d(TAG, String.format("任务【%s】已取消", mConfig.TEMP_FILE.getName()));
STATE.isRunning = false;
mListener.onCancel();
}
}
}
/**
* 线程任务失败
*
* @param subCurrentLocation 当前线程下载进度
* @param msg 自定义信息
* @param ex 异常信息
*/
protected void fail(final long subCurrentLocation, String msg, Exception ex) {
fail(subCurrentLocation, msg, ex, true);
}
/**
* 任务失败
*
* @param subCurrentLocation 当前子线程进度
*/
protected void fail(final long currentLocation, String msg, Exception ex) {
protected void fail(final long subCurrentLocation, String msg, Exception ex, boolean needRetry) {
synchronized (AriaManager.LOCK) {
try {
if (ex != null) {
ALog.e(TAG, msg + "\n" + ALog.getExceptionString(ex));
} else {
ALog.e(TAG, msg);
}
if (mConfig.SUPPORT_BP) {
writeConfig(false, currentLocation);
retryThis(STATE.START_THREAD_NUM != 1);
} else {
ALog.e(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】执行失败");
mListener.onFail(true);
ErrorHelp.saveError(TAG, "", ALog.getExceptionString(ex));
}
} catch (IOException e) {
e.printStackTrace();
if (ex != null) {
ALog.e(TAG, msg + "\n" + ALog.getExceptionString(ex));
} else {
ALog.e(TAG, msg);
}
if (mConfig.SUPPORT_BP) {
writeConfig(false, subCurrentLocation);
retryThis(needRetry && STATE.START_THREAD_NUM != 1);
} else {
ALog.e(TAG, String.format("任务【%s】执行失败", mConfig.TEMP_FILE.getName()));
mListener.onFail(true);
ErrorHelp.saveError(TAG, "", ALog.getExceptionString(ex));
}
}
}
@ -218,24 +250,21 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
mFailTimer.cancel();
}
if (!NetUtils.isConnected(AriaManager.APP) && !isNotNetRetry) {
ALog.w(TAG,
"任务【" + mConfig.TEMP_FILE.getName() + "】thread__" + mConfig.THREAD_ID + "__重试失败,网络未连接");
ALog.w(TAG, String.format("任务【%s】thread__%s__重试失败,网络未连接", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID));
}
if (mFailNum < RETRY_NUM
if (mFailTimes < RETRY_NUM
&& needRetry
&& NetUtils.isConnected(AriaManager.APP)
&& !isNotNetRetry
&& !STATE.isCancel
&& !STATE.isStop) {
&& (NetUtils.isConnected(AriaManager.APP) || isNotNetRetry)
&& isBreak()) {
mFailTimer = new Timer(true);
mFailTimer.schedule(new TimerTask() {
@Override public void run() {
mFailNum++;
ALog.w(TAG,
"任务【" + mConfig.TEMP_FILE.getName() + "】thread__" + mConfig.THREAD_ID + "__正在重试");
final long retryLocation =
mChildCurrentLocation == 0 ? mConfig.START_LOCATION : mChildCurrentLocation;
mConfig.START_LOCATION = retryLocation;
mFailTimes++;
ALog.w(TAG, String.format("任务【%s】thread__%s__正在重试", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID));
final long temp = mChildCurrentLocation;
mConfig.START_LOCATION = mChildCurrentLocation == 0 ? mConfig.START_LOCATION : temp;
AbsThreadTask.this.run();
}
}, RETRY_INTERVAL);
@ -244,7 +273,7 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
if (STATE.isFail()) {
STATE.isRunning = false;
STATE.isStop = true;
ALog.e(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】执行失败");
ALog.e(TAG, String.format("任务【%s】执行失败", mConfig.TEMP_FILE.getName()));
mListener.onFail(true);
}
}
@ -252,8 +281,11 @@ public abstract class AbsThreadTask<ENTITY extends AbsNormalEntity, TASK_ENTITY
/**
* 将记录写入到配置文件
*
* @param isComplete 当前线程是否完成 {@code true}完成
* @param record 当前下载进度
*/
protected void writeConfig(boolean isComplete, final long record) throws IOException {
protected void writeConfig(boolean isComplete, final long record) {
if (mConfig.THREAD_RECORD != null) {
mConfig.THREAD_RECORD.isComplete = isComplete;
if (0 < record && record < mConfig.END_LOCATION) {

@ -16,7 +16,6 @@
package com.arialyy.aria.core.common;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -29,7 +28,8 @@ import java.util.Set;
* 代理参数获取
*/
public class ProxyHelper {
public Set<String> downloadCounter, uploadCounter, downloadGroupCounter, downloadGroupSubCounter;
public Set<String> downloadCounter = new HashSet<>(), uploadCounter = new HashSet<>(),
downloadGroupCounter = new HashSet<>(), downloadGroupSubCounter = new HashSet<>();
public static volatile ProxyHelper INSTANCE = null;
@ -47,11 +47,9 @@ public class ProxyHelper {
}
private void init() {
List<String> classes = CommonUtil.getClassName(AriaManager.APP, "com.arialyy.aria");
List<String> classes = CommonUtil.getClassName(AriaManager.APP,
"com.arialyy.aria.ProxyClassCounter");
for (String className : classes) {
if (!className.startsWith("com.arialyy.aria.ProxyClassCounter")){
continue;
}
count(className);
}
}
@ -66,30 +64,18 @@ public class ProxyHelper {
Object object = clazz.newInstance();
Object dc = download.invoke(object);
if (dc != null) {
if (downloadCounter == null) {
downloadCounter = new HashSet<>();
}
downloadCounter.addAll((Set<String>) dc);
}
Object dgc = downloadGroup.invoke(object);
if (dgc != null) {
if (downloadGroupCounter == null) {
downloadGroupCounter = new HashSet<>();
}
downloadGroupCounter.addAll((Set<String>) dgc);
}
Object dgsc = downloadGroupSub.invoke(object);
if (dgsc != null) {
if (downloadGroupSubCounter == null) {
downloadGroupSubCounter = new HashSet<>();
}
downloadGroupSubCounter.addAll((Set<String>) dgsc);
}
Object uc = upload.invoke(object);
if (uc != null) {
if (uploadCounter == null) {
uploadCounter = new HashSet<>();
}
uploadCounter.addAll((Set<String>) uc);
}
} catch (ClassNotFoundException e) {

@ -30,6 +30,11 @@ public class StateConstance {
public boolean isCancel = false;
public boolean isStop = false;
public TaskRecord TASK_RECORD;
/**
* 是否是使用虚拟文件下载的
* {@code true}{@code false}不是
*/
public boolean isOpenDynamicFile = false;
public StateConstance() {
}

@ -73,10 +73,4 @@ public class TaskRecord extends DbEntity {
@Ignore
@Deprecated
public String uGroupName;
/**
* 是否是使用虚拟文件下载的
* {@code true}{@code false}不是
*/
public boolean isOpenDynamicFile = false;
}

@ -19,8 +19,6 @@ import android.os.Handler;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.common.TaskRecord;
import com.arialyy.aria.core.inf.AbsEntity;
import com.arialyy.aria.core.inf.AbsGroupEntity;
import com.arialyy.aria.core.inf.AbsNormalEntity;
import com.arialyy.aria.core.inf.AbsTask;
import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.core.inf.IDownloadListener;
@ -36,13 +34,13 @@ import java.lang.ref.WeakReference;
class BaseDListener<ENTITY extends AbsEntity, TASK_ENTITY extends AbsTaskEntity<ENTITY>, TASK extends AbsTask<TASK_ENTITY>>
implements IDownloadListener {
private static final String TAG = "BaseDListener";
protected WeakReference<Handler> outHandler;
WeakReference<Handler> outHandler;
private int RUN_SAVE_INTERVAL = 5 * 1000; //5s保存一次下载中的进度
private long mLastLen = 0; //上一次发送长度
private boolean isFirst = true;
protected ENTITY mEntity;
protected TASK_ENTITY mTaskEntity;
protected TASK mTask;
private TASK mTask;
private boolean isConvertSpeed = false;
boolean isWait = false;
private long mLastSaveTime;
@ -158,14 +156,16 @@ class BaseDListener<ENTITY extends AbsEntity, TASK_ENTITY extends AbsTaskEntity<
mEntity.setState(state);
mEntity.setComplete(state == IEntity.STATE_COMPLETE);
if (state == IEntity.STATE_CANCEL) {
if (mEntity instanceof AbsNormalEntity) {
if (mEntity instanceof DownloadEntity) {
TaskRecord record =
DbEntity.findFirst(TaskRecord.class, "TaskRecord.filePath=?", mTaskEntity.getKey());
if (record != null) {
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), (AbsNormalEntity) mEntity);
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), (DownloadEntity) mEntity);
} else {
mEntity.deleteData();
}
} else if (mEntity instanceof AbsGroupEntity) {
CommonUtil.delGroupTaskRecord(mTaskEntity.isRemoveFile(), ((AbsGroupEntity) mEntity));
} else if (mEntity instanceof DownloadGroupEntity) {
CommonUtil.delGroupTaskRecord(mTaskEntity.isRemoveFile(), ((DownloadGroupEntity) mEntity));
}
//mEntity.deleteData();
return;

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.aria.core.manager.SubTaskManager;
@ -49,6 +50,7 @@ abstract class BaseGroupTarget<TARGET extends BaseGroupTarget>
*
* @return 子任务管理器
*/
@CheckResult
public SubTaskManager getSubTaskManager() {
if (mSubTaskManager == null) {
mSubTaskManager = new SubTaskManager(mTargetName, mTaskEntity);
@ -59,6 +61,7 @@ abstract class BaseGroupTarget<TARGET extends BaseGroupTarget>
/**
* 设置任务组别名
*/
@CheckResult
public TARGET setGroupAlias(String alias) {
if (TextUtils.isEmpty(alias)) return (TARGET) this;
mEntity.setAlias(alias);
@ -76,6 +79,7 @@ abstract class BaseGroupTarget<TARGET extends BaseGroupTarget>
* @deprecated {@link #setDirPath(String)} 请使用这个api
*/
@Deprecated
@CheckResult
public TARGET setDownloadDirPath(String groupDirPath) {
return setDirPath(groupDirPath);
}
@ -99,6 +103,7 @@ abstract class BaseGroupTarget<TARGET extends BaseGroupTarget>
*
* @param dirPath 任务组保存文件夹路径
*/
@CheckResult
public TARGET setDirPath(String dirPath) {
mDirPathTemp = dirPath;
return (TARGET) this;

@ -136,8 +136,12 @@ abstract class BaseNormalTarget<TARGET extends BaseNormalTarget>
} else if (getTargetType() == FTP) {
filePath += mEntity.getFileName();
}
} else {
// http文件名设置
if (TextUtils.isEmpty(mEntity.getFileName())) {
mEntity.setFileName(file.getName());
}
}
mEntity.setFileName(file.getName());
//设置文件保存路径,如果新文件路径和就文件路径不同,则修改路径
if (!filePath.equals(mEntity.getDownloadPath())) {

@ -19,6 +19,7 @@ import android.os.Handler;
import com.arialyy.aria.core.download.downloader.IDownloadGroupListener;
import com.arialyy.aria.core.inf.GroupSendParams;
import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.util.ALog;
/**
* Created by Aria.Lao on 2017/7/20.
@ -85,10 +86,17 @@ class DownloadGroupListener
}
private void saveCurrentLocation() {
if (mEntity.getSubEntities() == null || mEntity.getSubEntities().isEmpty()) {
ALog.w(TAG, "保存进度失败,子任务为null");
return;
}
long location = 0;
for (DownloadEntity e : mEntity.getSubEntities()) {
location += e.getCurrentProgress();
}
if (location > mEntity.getFileSize()) {
location = mEntity.getFileSize();
}
mEntity.setCurrentProgress(location);
mEntity.update();
}

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.text.TextUtils;
import com.arialyy.aria.core.manager.TEManager;
import com.arialyy.aria.util.ALog;
@ -40,7 +41,7 @@ public class DownloadGroupTarget extends BaseGroupTarget<DownloadGroupTarget> {
*/
private List<String> mSubNameTemp = new ArrayList<>();
DownloadGroupTarget(DownloadGroupEntity groupEntity, String targetName) {
public DownloadGroupTarget(DownloadGroupEntity groupEntity, String targetName) {
this.mTargetName = targetName;
if (groupEntity.getUrls() != null && !groupEntity.getUrls().isEmpty()) {
this.mUrls.addAll(groupEntity.getUrls());
@ -72,6 +73,7 @@ public class DownloadGroupTarget extends BaseGroupTarget<DownloadGroupTarget> {
*
* @param fileSize 任务组总大小
*/
@CheckResult
public DownloadGroupTarget setFileSize(long fileSize) {
if (fileSize <= 0) {
ALog.e(TAG, "文件大小不能小于 0");
@ -86,6 +88,7 @@ public class DownloadGroupTarget extends BaseGroupTarget<DownloadGroupTarget> {
/**
* 如果你是使用{@link DownloadReceiver#load(DownloadGroupEntity)}进行下载操作那么你需要设置任务组的下载地址
*/
@CheckResult
public DownloadGroupTarget setGroupUrl(List<String> urls) {
mUrls.clear();
mUrls.addAll(urls);
@ -97,6 +100,7 @@ public class DownloadGroupTarget extends BaseGroupTarget<DownloadGroupTarget> {
*
* @deprecated {@link #setSubFileName(List)} 请使用该api
*/
@CheckResult
@Deprecated public DownloadGroupTarget setSubTaskFileName(List<String> subTaskFileName) {
return setSubFileName(subTaskFileName);
}
@ -104,6 +108,7 @@ public class DownloadGroupTarget extends BaseGroupTarget<DownloadGroupTarget> {
/**
* 设置子任务文件名该方法必须在{@link #setDirPath(String)}之后调用否则不生效
*/
@CheckResult
public DownloadGroupTarget setSubFileName(List<String> subTaskFileName) {
if (subTaskFileName == null || subTaskFileName.isEmpty()) {
ALog.e(TAG, "修改子任务的文件名失败:列表为null");

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaManager;
@ -59,6 +60,7 @@ public class DownloadReceiver extends AbsReceiver {
*
* @param entity 下载实体
*/
@CheckResult
public DownloadTarget load(DownloadEntity entity) {
return load(entity, false);
}
@ -78,6 +80,7 @@ public class DownloadReceiver extends AbsReceiver {
* </code>
* </pre>
*/
@CheckResult
@Deprecated public DownloadTarget load(DownloadEntity entity, boolean refreshInfo) {
CheckUtil.checkDownloadEntity(entity);
return new DownloadTarget(entity, targetName, refreshInfo);
@ -88,6 +91,7 @@ public class DownloadReceiver extends AbsReceiver {
*
* @param url 下载地址
*/
@CheckResult
public DownloadTarget load(@NonNull String url) {
return load(url, false);
}
@ -108,6 +112,7 @@ public class DownloadReceiver extends AbsReceiver {
* </code>
* </pre>
*/
@CheckResult
@Deprecated public DownloadTarget load(@NonNull String url, boolean refreshInfo) {
CheckUtil.checkUrlInvalidThrow(url);
return new DownloadTarget(url, targetName, refreshInfo);
@ -120,6 +125,7 @@ public class DownloadReceiver extends AbsReceiver {
* @deprecated {@link #loadGroup(DownloadGroupEntity)}
*/
@Deprecated
@CheckResult
public DownloadGroupTarget load(List<String> urls) {
return loadGroup(urls);
}
@ -127,6 +133,7 @@ public class DownloadReceiver extends AbsReceiver {
/**
* 加载下载地址如果任务组的中的下载地址改变了则任务从新的一个任务组
*/
@CheckResult
public DownloadGroupTarget loadGroup(List<String> urls) {
CheckUtil.checkDownloadUrls(urls);
return new DownloadGroupTarget(urls, targetName);
@ -137,6 +144,7 @@ public class DownloadReceiver extends AbsReceiver {
*
* @param entity 下载实体
*/
@CheckResult
public FtpDownloadTarget loadFtp(DownloadEntity entity) {
return loadFtp(entity, false);
}
@ -156,6 +164,7 @@ public class DownloadReceiver extends AbsReceiver {
* </code>
* </pre>
*/
@CheckResult
@Deprecated public FtpDownloadTarget loadFtp(DownloadEntity entity, boolean refreshInfo) {
CheckUtil.checkDownloadEntity(entity);
if (!entity.getUrl().startsWith("ftp")) {
@ -167,6 +176,7 @@ public class DownloadReceiver extends AbsReceiver {
/**
* 加载ftp单任务下载地址
*/
@CheckResult
public FtpDownloadTarget loadFtp(@NonNull String url) {
return loadFtp(url, false);
}
@ -176,6 +186,7 @@ public class DownloadReceiver extends AbsReceiver {
*
* @param refreshInfo 是否刷新下载信息
*/
@CheckResult
public FtpDownloadTarget loadFtp(@NonNull String url, boolean refreshInfo) {
CheckUtil.checkUrlInvalidThrow(url);
return new FtpDownloadTarget(url, targetName, refreshInfo);
@ -189,6 +200,7 @@ public class DownloadReceiver extends AbsReceiver {
* @deprecated 请使用 {@link #loadGroup(DownloadGroupEntity)}
*/
@Deprecated
@CheckResult
public DownloadGroupTarget load(DownloadGroupEntity groupEntity) {
return loadGroup(groupEntity);
}
@ -199,6 +211,7 @@ public class DownloadReceiver extends AbsReceiver {
* @param groupEntity 如果加载的任务实体没有子项的下载地址
* 那么你需要使用{@link DownloadGroupTarget#setGroupUrl(List)}设置子项的下载地址
*/
@CheckResult
public DownloadGroupTarget loadGroup(DownloadGroupEntity groupEntity) {
return new DownloadGroupTarget(groupEntity, targetName);
}
@ -206,6 +219,7 @@ public class DownloadReceiver extends AbsReceiver {
/**
* 加载ftp文件夹下载地址
*/
@CheckResult
public FtpDirDownloadTarget loadFtpDir(@NonNull String dirUrl) {
CheckUtil.checkUrlInvalidThrow(dirUrl);
return new FtpDirDownloadTarget(dirUrl, targetName);
@ -214,7 +228,7 @@ public class DownloadReceiver extends AbsReceiver {
/**
* 将当前类注册到Aria
*/
public DownloadReceiver register() {
public void register() {
String className = obj.getClass().getName();
Set<String> dCounter = ProxyHelper.getInstance().downloadCounter;
Set<String> dgCounter = ProxyHelper.getInstance().downloadGroupCounter;
@ -226,7 +240,6 @@ public class DownloadReceiver extends AbsReceiver {
&& dgsCounter.contains(className))) {
DownloadGroupSchedulers.getInstance().register(obj);
}
return this;
}
/**
@ -265,7 +278,7 @@ public class DownloadReceiver extends AbsReceiver {
* @return 如果url错误或查找不到数据则返回null
*/
public DownloadEntity getDownloadEntity(String downloadUrl) {
if (CheckUtil.checkUrl(downloadUrl)) {
if (!CheckUtil.checkUrl(downloadUrl)) {
return null;
}
return DbEntity.findFirst(DownloadEntity.class, "url=? and isGroupChild='false'", downloadUrl);
@ -278,7 +291,10 @@ public class DownloadReceiver extends AbsReceiver {
* @return 如果url错误或查找不到数据则返回null
*/
public DownloadTaskEntity getDownloadTask(String downloadUrl) {
if (CheckUtil.checkUrl(downloadUrl)) {
if (!CheckUtil.checkUrl(downloadUrl)) {
return null;
}
if (!taskExists(downloadUrl)) {
return null;
}
return TEManager.getInstance().getTEntity(DownloadTaskEntity.class, downloadUrl);
@ -295,6 +311,9 @@ public class DownloadReceiver extends AbsReceiver {
ALog.e(TAG, "获取任务组实体失败:任务组子任务下载地址列表为null");
return null;
}
if (!taskExists(urls)) {
return null;
}
return TEManager.getInstance().getGTEntity(DownloadGroupTaskEntity.class, urls);
}
@ -309,6 +328,11 @@ public class DownloadReceiver extends AbsReceiver {
ALog.e(TAG, "获取FTP文件夹实体失败:下载路径为null");
return null;
}
boolean b =
DownloadGroupEntity.findFirst(DownloadGroupEntity.class, "groupName=?", dirUrl) != null;
if (!b) {
return null;
}
return TEManager.getInstance().getFDTEntity(DownloadGroupTaskEntity.class, dirUrl);
}
@ -319,6 +343,20 @@ public class DownloadReceiver extends AbsReceiver {
return DownloadEntity.findFirst(DownloadEntity.class, "url=?", downloadUrl) != null;
}
/**
* 判断任务组是否存在
*
* @return {@code true} 存在{@code false} 不存在
*/
public boolean taskExists(List<String> urls) {
if (urls == null || urls.isEmpty()) {
return false;
}
String groupName = CommonUtil.getMd5Code(urls);
return DownloadGroupEntity.findFirst(DownloadGroupEntity.class, "groupName=?", groupName)
!= null;
}
/**
* 获取所有普通下载任务
* 获取未完成的普通任务列表{@link #getAllNotCompletTask()}

@ -15,10 +15,12 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.core.delegate.HttpHeaderDelegate;
import com.arialyy.aria.core.inf.IHttpHeaderTarget;
import java.net.Proxy;
import java.util.Map;
/**
@ -29,7 +31,7 @@ public class DownloadTarget extends BaseNormalTarget<DownloadTarget>
implements IHttpHeaderTarget<DownloadTarget> {
private HttpHeaderDelegate<DownloadTarget, DownloadEntity, DownloadTaskEntity> mDelegate;
DownloadTarget(DownloadEntity entity, String targetName) {
public DownloadTarget(DownloadEntity entity, String targetName) {
this(entity, targetName, false);
}
@ -52,11 +54,23 @@ public class DownloadTarget extends BaseNormalTarget<DownloadTarget>
*
* @param use {@code true} 使用
*/
@CheckResult
public DownloadTarget useServerFileName(boolean use) {
mTaskEntity.setUseServerFileName(use);
return this;
}
/**
* 设置URL的代理
*
* @param proxy {@link Proxy}
*/
@CheckResult
public DownloadTarget setUrlProxy(Proxy proxy) {
mTaskEntity.setProxy(proxy);
return this;
}
/**
* 设置文件存储路径
* 该api后续版本会删除
@ -64,6 +78,7 @@ public class DownloadTarget extends BaseNormalTarget<DownloadTarget>
* @param downloadPath 文件保存路径
* @deprecated {@link #setFilePath(String)} 请使用这个api
*/
@CheckResult
@Deprecated public DownloadTarget setDownloadPath(@NonNull String downloadPath) {
return setFilePath(downloadPath);
}
@ -75,6 +90,7 @@ public class DownloadTarget extends BaseNormalTarget<DownloadTarget>
*
* @param filePath 路径必须为文件路径不能为文件夹路径
*/
@CheckResult
public DownloadTarget setFilePath(@NonNull String filePath) {
mTempFilePath = filePath;
return this;
@ -91,14 +107,17 @@ public class DownloadTarget extends BaseNormalTarget<DownloadTarget>
return HTTP;
}
@CheckResult
@Override public DownloadTarget addHeader(@NonNull String key, @NonNull String value) {
return mDelegate.addHeader(key, value);
}
@CheckResult
@Override public DownloadTarget addHeaders(Map<String, String> headers) {
return mDelegate.addHeaders(headers);
}
@CheckResult
@Override public DownloadTarget setRequestMode(RequestEnum requestEnum) {
return mDelegate.setRequestMode(requestEnum);
}

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.text.TextUtils;
import com.arialyy.aria.core.delegate.FtpDelegate;
import com.arialyy.aria.core.inf.AbsTaskEntity;
@ -89,15 +90,15 @@ public class FtpDirDownloadTarget extends BaseGroupTarget<FtpDirDownloadTarget>
}
return true;
}
@CheckResult
@Override public FtpDirDownloadTarget charSet(String charSet) {
return mDelegate.charSet(charSet);
}
@CheckResult
@Override public FtpDirDownloadTarget login(String userName, String password) {
return mDelegate.login(userName, password);
}
@CheckResult
@Override public FtpDirDownloadTarget login(String userName, String password, String account) {
return mDelegate.login(userName, password, account);
}

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.download;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.delegate.FtpDelegate;
import com.arialyy.aria.core.inf.AbsTaskEntity;
@ -29,7 +30,7 @@ public class FtpDownloadTarget extends BaseNormalTarget<FtpDownloadTarget>
implements IFtpTarget<FtpDownloadTarget> {
private FtpDelegate<FtpDownloadTarget, DownloadEntity, DownloadTaskEntity> mDelegate;
FtpDownloadTarget(DownloadEntity entity, String targetName, boolean refreshInfo) {
public FtpDownloadTarget(DownloadEntity entity, String targetName, boolean refreshInfo) {
this(entity.getUrl(), targetName, refreshInfo);
}
@ -59,6 +60,7 @@ public class FtpDownloadTarget extends BaseNormalTarget<FtpDownloadTarget>
* @deprecated {@link #setFilePath(String)} 请使用这个api
*/
@Deprecated
@CheckResult
public FtpDownloadTarget setDownloadPath(@NonNull String filePath) {
return setFilePath(filePath);
}
@ -69,6 +71,7 @@ public class FtpDownloadTarget extends BaseNormalTarget<FtpDownloadTarget>
* 1如果保存路径是该文件的保存路径/mnt/sdcard/file.zip则使用路径中的文件名file.zip
* 2如果保存路径是文件夹路径/mnt/sdcard/则使用FTP服务器该文件的文件名
*/
@CheckResult
public FtpDownloadTarget setFilePath(@NonNull String filePath) {
mTempFilePath = filePath;
return this;
@ -78,14 +81,17 @@ public class FtpDownloadTarget extends BaseNormalTarget<FtpDownloadTarget>
return FTP;
}
@CheckResult
@Override public FtpDownloadTarget charSet(String charSet) {
return mDelegate.charSet(charSet);
}
@CheckResult
@Override public FtpDownloadTarget login(String userName, String password) {
return mDelegate.login(userName, password);
}
@CheckResult
@Override public FtpDownloadTarget login(String userName, String password, String account) {
return mDelegate.login(userName, password, account);
}

@ -39,15 +39,16 @@ import java.util.concurrent.Executors;
* 任务组核心逻辑
*/
public abstract class AbsGroupUtil implements IUtil {
private static final Object LOCK = new Object();
private final String TAG = "AbsGroupUtil";
/**
* FTP文件夹
*/
protected int FTP_DIR = 0xa1;
int FTP_DIR = 0xa1;
/**
* HTTP 任务组
*/
protected int HTTP_GROUP = 0xa2;
int HTTP_GROUP = 0xa2;
/**
* 任务组所有任务总长度
@ -56,7 +57,7 @@ public abstract class AbsGroupUtil implements IUtil {
long mCurrentLocation = 0;
private ExecutorService mExePool;
protected IDownloadGroupListener mListener;
protected DownloadGroupTaskEntity mGTEntity;
DownloadGroupTaskEntity mGTEntity;
private boolean isRunning = false;
private Timer mTimer;
/**
@ -158,6 +159,9 @@ public abstract class AbsGroupUtil implements IUtil {
DownloadTaskEntity det = mTasksMap.get(url);
if (det != null) {
mTotalLen -= det.getEntity().getFileSize();
mCurrentLocation -= det.getEntity().getCurrentProgress();
mExeMap.remove(det.getKey());
mFailMap.remove(det.getKey());
mGroupSize--;
if (mGroupSize == 0) {
closeTimer(false);
@ -255,6 +259,9 @@ public abstract class AbsGroupUtil implements IUtil {
dt.stop();
}
}
if (mDownloaderMap.size() == 0){
mListener.onStop(mCurrentLocation);
}
}
protected void onStop() {
@ -262,7 +269,7 @@ public abstract class AbsGroupUtil implements IUtil {
}
/**
* 预处理操作由于属性的不同http任务组在构造函数中就可以完成了
* 预处理操作
* 而FTP文件夹的需要获取完成所有子任务信息才算预处理完成
*/
protected void onPre() {
@ -284,7 +291,6 @@ public abstract class AbsGroupUtil implements IUtil {
}
mTasksMap.put(te.getUrl(), te);
}
updateFileSize();
}
@Override public void start() {
@ -299,19 +305,18 @@ public abstract class AbsGroupUtil implements IUtil {
@Override public void resume() {
start();
mListener.onResume(mCurrentLocation);
}
@Override public void setMaxSpeed(double maxSpeed) {
}
private void clearState(){
private void clearState() {
mDownloaderMap.clear();
mFailMap.clear();
}
private void closeTimer(boolean isRunning) {
void closeTimer(boolean isRunning) {
this.isRunning = isRunning;
if (mTimer != null) {
mTimer.purge();
@ -326,7 +331,11 @@ public abstract class AbsGroupUtil implements IUtil {
void startRunningFlow() {
closeTimer(true);
mListener.onPostPre(mTotalLen);
mListener.onStart(mCurrentLocation);
if (mCurrentLocation > 0) {
mListener.onResume(mCurrentLocation);
} else {
mListener.onStart(mCurrentLocation);
}
startTimer();
}
@ -337,7 +346,16 @@ public abstract class AbsGroupUtil implements IUtil {
if (!isRunning) {
closeTimer(false);
} else if (mCurrentLocation >= 0) {
mListener.onProgress(mCurrentLocation);
long t = 0;
for (DownloadTaskEntity te : mGTEntity.getSubTaskEntities()) {
if (te.getState() == IEntity.STATE_COMPLETE) {
t += te.getEntity().getFileSize();
} else {
t += te.getEntity().getCurrentProgress();
}
}
mCurrentLocation = t;
mListener.onProgress(t);
}
}
}, 0, mUpdateInterval);
@ -346,8 +364,8 @@ public abstract class AbsGroupUtil implements IUtil {
/**
* 创建子任务下载器默认创建完成自动启动
*/
Downloader createChildDownload(DownloadTaskEntity taskEntity) {
return createChildDownload(taskEntity, true);
void createChildDownload(DownloadTaskEntity taskEntity) {
createChildDownload(taskEntity, true);
}
/**
@ -375,6 +393,8 @@ public abstract class AbsGroupUtil implements IUtil {
private int RUN_SAVE_INTERVAL = 5 * 1000; //5s保存一次下载中的进度
private long lastSaveTime;
private long lastLen = 0;
private Timer timer;
private boolean isNotNetRetry = false;
ChildDownloadListener(DownloadTaskEntity entity) {
subTaskEntity = entity;
@ -382,6 +402,7 @@ public abstract class AbsGroupUtil implements IUtil {
subEntity.setFailNum(0);
lastLen = subEntity.getCurrentProgress();
lastSaveTime = System.currentTimeMillis();
isNotNetRetry = AriaManager.getInstance(AriaManager.APP).getDownloadConfig().isNotNetRetry();
}
@Override public void onPre() {
@ -409,7 +430,7 @@ public abstract class AbsGroupUtil implements IUtil {
@Override public void onProgress(long currentLocation) {
long speed = currentLocation - lastLen;
mCurrentLocation += speed;
//mCurrentLocation += speed;
subEntity.setCurrentProgress(currentLocation);
handleSpeed(speed);
mListener.onSubRunning(subEntity);
@ -424,7 +445,7 @@ public abstract class AbsGroupUtil implements IUtil {
saveData(IEntity.STATE_STOP, stopLocation);
handleSpeed(0);
mListener.onSubStop(subEntity);
synchronized (AbsGroupUtil.class) {
synchronized (AbsGroupUtil.LOCK) {
mStopNum++;
if (mStopNum + mCompleteNum + mFailMap.size() == mGroupSize) {
closeTimer(false);
@ -440,16 +461,17 @@ public abstract class AbsGroupUtil implements IUtil {
}
@Override public void onComplete() {
subEntity.setComplete(true);
saveData(IEntity.STATE_COMPLETE, subEntity.getFileSize());
handleSpeed(0);
mListener.onSubComplete(subEntity);
synchronized (ChildDownloadListener.class) {
synchronized (AbsGroupUtil.LOCK) {
mCompleteNum++;
//如果子任务完成的数量和总任务数一致,表示任务组任务已经完成
if (mCompleteNum >= mGroupSize) {
if (mCompleteNum == mGroupSize) {
closeTimer(false);
mListener.onComplete();
} else if (mFailMap.size() > 0 && mStopNum + mCompleteNum + mFailMap.size() >= mGroupSize) {
} else if (mFailMap.size() > 0 && mStopNum + mCompleteNum + mFailMap.size() == mGroupSize) {
//如果子任务完成数量加上失败的数量和总任务数一致,则任务组停止下载
closeTimer(false);
mListener.onStop(mCurrentLocation);
@ -465,41 +487,48 @@ public abstract class AbsGroupUtil implements IUtil {
}
/**
* 重试下载
* 重试下载只有全部都下载失败才会执行任务组的整体重试否则只会执行单个子任务的重试
*/
private void reTry(boolean needRetry) {
synchronized (ChildDownloadListener.class) {
if (subEntity.getFailNum() < 5 && needRetry && NetUtils.isConnected(AriaManager.APP)) {
synchronized (AbsGroupUtil.LOCK) {
if (subEntity.getFailNum() < 5
&& needRetry && (NetUtils.isConnected(AriaManager.APP) || isNotNetRetry)) {
reStartTask();
} else {
mFailMap.put(subTaskEntity.getUrl(), subTaskEntity);
mListener.onSubFail(subEntity);
//如果失败的任务数大于实际的下载任务数,任务组停止下载
if (mFailMap.size() >= mExeMap.size()) {
if (mFailMap.size() == mExeMap.size() || mFailMap.size() + mCompleteNum == mGroupSize) {
closeTimer(false);
if (mFailMap.size() == mGroupSize) { //所有任务都失败了,则认为该任务组已经失败
mListener.onFail(true);
} else {
mListener.onStop(mCurrentLocation);
}
}
if (mFailMap.size() == mGroupSize) {
mListener.onFail(true);
} else if (mFailMap.size() + mCompleteNum >= mExeMap.size()) {
mListener.onStop(mCurrentLocation);
}
}
}
}
private void reStartTask() {
Timer timer = new Timer();
if (timer != null) {
timer.purge();
timer.cancel();
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override public void run() {
Downloader dt = mDownloaderMap.get(subEntity.getUrl());
dt.start();
if (dt != null) {
dt.retryThreadTask();
}
}
}, 3000);
}
private void handleSpeed(long speed) {
subEntity.setSpeed(speed);
subEntity.setConvertSpeed(speed <= 0 ? "" : CommonUtil.formatFileSize(speed) + "/s");
subEntity.setConvertSpeed(
speed <= 0 ? "" : String.format("%s/s", CommonUtil.formatFileSize(speed)));
subEntity.setPercent((int) (subEntity.getFileSize() <= 0 ? 0
: subEntity.getCurrentProgress() * 100 / subEntity.getFileSize()));
}

@ -16,7 +16,9 @@
package com.arialyy.aria.core.download.downloader;
import android.text.TextUtils;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.util.SSLContextUtil;
import java.io.IOException;
import java.io.InputStream;
@ -44,7 +46,7 @@ class ConnectionHelp {
* @throws IOException
*/
static InputStream convertInputStream(HttpURLConnection connection) throws IOException {
String encoding = connection.getContentEncoding();
String encoding = connection.getHeaderField("Content-Encoding");
if (TextUtils.isEmpty(encoding)) {
return connection.getInputStream();
}
@ -62,9 +64,14 @@ class ConnectionHelp {
*
* @throws IOException
*/
static HttpURLConnection handleConnection(URL url) throws IOException {
static HttpURLConnection handleConnection(URL url, AbsTaskEntity taskEntity) throws IOException {
HttpURLConnection conn;
URLConnection urlConn = url.openConnection();
URLConnection urlConn;
if (taskEntity.getProxy() != null) {
urlConn = url.openConnection(taskEntity.getProxy());
} else {
urlConn = url.openConnection();
}
if (urlConn instanceof HttpsURLConnection) {
conn = (HttpsURLConnection) urlConn;
SSLContext sslContext =
@ -86,9 +93,10 @@ class ConnectionHelp {
*
* @throws ProtocolException
*/
static HttpURLConnection setConnectParam(DownloadTaskEntity entity, HttpURLConnection conn)
throws ProtocolException {
conn.setRequestMethod(entity.getRequestEnum().name);
static HttpURLConnection setConnectParam(DownloadTaskEntity entity, HttpURLConnection conn) {
if (entity.getRequestEnum() == RequestEnum.POST) {
conn.setDoInput(true);
}
Set<String> keys = null;
if (entity.getHeaders() != null && entity.getHeaders().size() > 0) {
keys = entity.getHeaders().keySet();

@ -34,7 +34,17 @@ import java.util.concurrent.Executors;
public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
private final String TAG = "DownloadGroupUtil";
private ExecutorService mInfoPool;
private int mInitCompleteNum, mInitFailNum;
/**
* 初始化完成的任务数
*/
private int mInitCompleteNum;
/**
* 初始化失败的任务数
*/
private int mInitFailNum;
private boolean isStop = false;
private boolean isStart = false;
private int mExeNum;
/**
* 文件信息回调组
@ -44,7 +54,6 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
public DownloadGroupUtil(IDownloadGroupListener listener, DownloadGroupTaskEntity taskEntity) {
super(listener, taskEntity);
mInfoPool = Executors.newCachedThreadPool();
onPre();
}
@Override int getTaskType() {
@ -53,6 +62,7 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
@Override public void onCancel() {
super.onCancel();
isStop = true;
if (!mInfoPool.isShutdown()) {
mInfoPool.shutdown();
}
@ -60,13 +70,15 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
@Override protected void onStop() {
super.onStop();
isStop = true;
if (!mInfoPool.isShutdown()) {
mInfoPool.shutdown();
}
}
@Override protected void onStart() {
super.onStart();
onPre();
isStop = false;
if (mCompleteNum == mGroupSize) {
mListener.onComplete();
return;
@ -78,12 +90,15 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
return;
}
Set<String> keys = mExeMap.keySet();
mExeNum = mExeMap.size();
for (String key : keys) {
DownloadTaskEntity taskEntity = mExeMap.get(key);
if (taskEntity != null) {
if (taskEntity.getState() != IEntity.STATE_FAIL
&& taskEntity.getState() != IEntity.STATE_WAIT) {
mInitCompleteNum++;
createChildDownload(taskEntity);
checkStartFlow();
} else {
mInfoPool.execute(createFileInfoThread(taskEntity));
}
@ -105,6 +120,7 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
int failNum = 0;
@Override public void onComplete(String url, CompleteInfo info) {
if (isStop) return;
DownloadTaskEntity te = mExeMap.get(url);
if (te != null) {
if (isNeedLoadFileSize) {
@ -112,16 +128,14 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
}
createChildDownload(te);
}
mInitCompleteNum ++;
mInitCompleteNum++;
if (mInitCompleteNum + mInitFailNum >= mGroupSize || !isNeedLoadFileSize) {
startRunningFlow();
updateFileSize();
}
checkStartFlow();
}
@Override public void onFail(String url, String errorMsg, boolean needRetry) {
ALog.e(TAG, "任务【" + url + "】初始化失败。");
if (isStop) return;
ALog.e(TAG, String.format("任务【%s】初始化失败", url));
DownloadTaskEntity te = mExeMap.get(url);
if (te != null) {
mFailMap.put(url, te);
@ -136,14 +150,28 @@ public class DownloadGroupUtil extends AbsGroupUtil implements IUtil {
// mInitFailNum++;
//}
//failNum++;
mInitFailNum ++;
if (mInitCompleteNum + mInitFailNum >= mGroupSize || !isNeedLoadFileSize) {
startRunningFlow();
updateFileSize();
}
mInitFailNum++;
checkStartFlow();
}
};
}
return new HttpFileInfoThread(taskEntity, callback);
}
/**
* 检查能否启动下载流程
*/
private void checkStartFlow() {
synchronized (DownloadGroupUtil.class) {
if (mInitFailNum == mExeNum) {
closeTimer(false);
mListener.onFail(true);
}
if (!isStart && mInitCompleteNum + mInitFailNum == mExeNum || !isNeedLoadFileSize) {
startRunningFlow();
updateFileSize();
isStart = true;
}
}
}
}

@ -45,23 +45,26 @@ class Downloader extends AbsFileer<DownloadEntity, DownloadTaskEntity> {
}
@Override protected int setNewTaskThreadNum() {
int threadNum = AriaManager.getInstance(mContext).getDownloadConfig().getThreadNum();
return
// 小于1m的文件或是任务组的子任务、使用虚拟文件,线程数都是1
mEntity.getFileSize() <= SUB_LEN
|| mTaskEntity.getRequestType() == AbsTaskEntity.D_FTP_DIR
|| mTaskEntity.getRequestType() == AbsTaskEntity.DG_HTTP
|| mRecord.isOpenDynamicFile
|| threadNum == 1
? 1
: AriaManager.getInstance(mContext).getDownloadConfig().getThreadNum();
: threadNum;
}
@Override protected boolean handleNewTask() {
CommonUtil.createFile(mTempFile.getPath());
BufferedRandomAccessFile file = null;
try {
file = new BufferedRandomAccessFile(new File(mTempFile.getPath()), "rwd", 8192);
//设置文件长度
file.setLength(mRecord.isOpenDynamicFile ? 1 : mEntity.getFileSize());
if (mTotalThreadNum > 1) {
file = new BufferedRandomAccessFile(new File(mTempFile.getPath()), "rwd", 8192);
//设置文件长度
file.setLength(mEntity.getFileSize());
}
return true;
} catch (IOException e) {
failDownload("下载失败【downloadUrl:"

@ -24,8 +24,13 @@ import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.IDownloadListener;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.BufferedRandomAccessFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
@ -36,10 +41,6 @@ import org.apache.commons.net.ftp.FTPReply;
class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity> {
private final String TAG = "FtpThreadTask";
private boolean isOpenDynamicFile;
/**
* 2M的动态长度
*/
private final int LEN_INTERVAL = 1024 * 1024 * 2;
FtpThreadTask(StateConstance constance, IDownloadListener listener,
SubThreadConfig<DownloadTaskEntity> downloadInfo) {
@ -49,7 +50,7 @@ class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity>
mReadTimeOut = manager.getDownloadConfig().getIOTimeOut();
mBufSize = manager.getDownloadConfig().getBuffSize();
isNotNetRetry = manager.getDownloadConfig().isNotNetRetry();
isOpenDynamicFile = STATE.TASK_RECORD.isOpenDynamicFile;
isOpenDynamicFile = STATE.isOpenDynamicFile;
setMaxSpeed(manager.getDownloadConfig().getMaxSpeed());
}
@ -58,17 +59,11 @@ class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity>
mChildCurrentLocation = mConfig.START_LOCATION;
FTPClient client = null;
InputStream is = null;
BufferedRandomAccessFile file = null;
try {
ALog.d(TAG, "任务【"
+ mConfig.TEMP_FILE.getName()
+ "】线程__"
+ mConfig.THREAD_ID
+ "__开始下载【开始位置 : "
+ mConfig.START_LOCATION
+ ",结束位置:"
+ mConfig.END_LOCATION
+ "】");
ALog.d(TAG,
String.format("任务【%s】线程__%s__开始下载【开始位置 : %s,结束位置:%s】", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID, mConfig.START_LOCATION, mConfig.END_LOCATION));
client = createClient();
if (client == null) return;
if (mConfig.START_LOCATION > 0) {
@ -77,51 +72,37 @@ class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity>
//发送第二次指令时,还需要再做一次判断
int reply = client.getReplyCode();
if (!FTPReply.isPositivePreliminary(reply) && reply != FTPReply.COMMAND_OK) {
fail(mChildCurrentLocation, "获取文件信息错误,错误码为:" + reply + ",msg:" + client.getReplyString(),
fail(mChildCurrentLocation,
String.format("获取文件信息错误,错误码为:%s,msg:%s", reply, client.getReplyString()),
null);
client.disconnect();
return;
}
String remotePath =
new String(mTaskEntity.getUrlEntity().remotePath.getBytes(charSet), SERVER_CHARSET);
ALog.i(TAG, "remotePath【" + remotePath + "】");
ALog.i(TAG, String.format("remotePath【%s】", remotePath));
is = client.retrieveFileStream(remotePath);
reply = client.getReplyCode();
if (!FTPReply.isPositivePreliminary(reply)) {
fail(mChildCurrentLocation, "获取流失败,错误码为:" + reply + ",msg:" + client.getReplyString(),
fail(mChildCurrentLocation,
String.format("获取流失败,错误码为:%s,msg:%s", reply, client.getReplyString()),
null);
client.disconnect();
return;
}
file = new BufferedRandomAccessFile(mConfig.TEMP_FILE, "rwd", mBufSize);
file.seek(mConfig.START_LOCATION);
byte[] buffer = new byte[mBufSize];
int len;
if (isOpenDynamicFile) {
readDynamicFile(is);
} else {
readNormal(is);
}
while ((len = is.read(buffer)) != -1) {
if (STATE.isCancel || STATE.isStop) {
break;
}
if (mSleepTime > 0) Thread.sleep(mSleepTime);
if (isOpenDynamicFile) {
file.setLength(
STATE.CURRENT_LOCATION + LEN_INTERVAL < mEntity.getFileSize() ? STATE.CURRENT_LOCATION
+ LEN_INTERVAL : mEntity.getFileSize());
}
if (mChildCurrentLocation + len >= mConfig.END_LOCATION) {
len = (int) (mConfig.END_LOCATION - mChildCurrentLocation);
file.write(buffer, 0, len);
progress(len);
break;
} else {
file.write(buffer, 0, len);
progress(len);
}
if (isBreak()) {
return;
}
if (STATE.isCancel || STATE.isStop) return;
ALog.i(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】线程__" + mConfig.THREAD_ID + "__下载完毕");
writeConfig(true, 1);
ALog.i(TAG,
String.format("任务【%s】线程__%s__下载完毕", mConfig.TEMP_FILE.getName(), mConfig.THREAD_ID));
writeConfig(true, mConfig.END_LOCATION);
STATE.COMPLETE_THREAD_NUM++;
if (STATE.isComplete()) {
STATE.TASK_RECORD.deleteData();
@ -133,14 +114,11 @@ class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity>
mListener.onFail(false);
}
} catch (IOException e) {
fail(mChildCurrentLocation, "下载失败【" + mConfig.URL + "】", e);
fail(mChildCurrentLocation, String.format("下载失败【%s】", mConfig.URL), e);
} catch (Exception e) {
fail(mChildCurrentLocation, "获取流失败", e);
} finally {
try {
if (file != null) {
file.close();
}
if (is != null) {
is.close();
}
@ -153,7 +131,89 @@ class FtpThreadTask extends AbsFtpThreadTask<DownloadEntity, DownloadTaskEntity>
}
}
@Override protected String getTaskType() {
return "FTP_DOWNLOAD";
/**
* 动态长度文件读取方式
*/
private void readDynamicFile(InputStream is) {
FileOutputStream fos = null;
FileChannel foc = null;
ReadableByteChannel fic = null;
try {
int len;
fos = new FileOutputStream(mConfig.TEMP_FILE, true);
foc = fos.getChannel();
fic = Channels.newChannel(is);
ByteBuffer bf = ByteBuffer.allocate(mBufSize);
while ((len = fic.read(bf)) != -1) {
if (isBreak()) {
break;
}
if (mSleepTime > 0) {
Thread.sleep(mSleepTime);
}
bf.flip();
foc.write(bf);
bf.compact();
progress(len);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
fail(mChildCurrentLocation, String.format("下载失败【%s】", mConfig.URL), e);
} finally {
try {
if (fos != null) {
fos.close();
}
if (foc != null) {
foc.close();
}
if (fic != null) {
fic.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 多线程写文件方式
*/
private void readNormal(InputStream is) {
BufferedRandomAccessFile file = null;
try {
file = new BufferedRandomAccessFile(mConfig.TEMP_FILE, "rwd", mBufSize);
file.seek(mConfig.START_LOCATION);
byte[] buffer = new byte[mBufSize];
int len;
while ((len = is.read(buffer)) != -1) {
if (isBreak()) {
break;
}
if (mSleepTime > 0) Thread.sleep(mSleepTime);
if (mChildCurrentLocation + len >= mConfig.END_LOCATION) {
len = (int) (mConfig.END_LOCATION - mChildCurrentLocation);
file.write(buffer, 0, len);
progress(len);
break;
} else {
file.write(buffer, 0, len);
progress(len);
}
}
} catch (IOException e) {
fail(mChildCurrentLocation, String.format("下载失败【%s】", mConfig.URL), e);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

@ -54,7 +54,7 @@ class HttpFileInfoThread implements Runnable {
HttpURLConnection conn = null;
try {
URL url = new URL(CommonUtil.convertUrl(mEntity.getUrl()));
conn = ConnectionHelp.handleConnection(url);
conn = ConnectionHelp.handleConnection(url, mTaskEntity);
conn = ConnectionHelp.setConnectParam(mTaskEntity, conn);
conn.setRequestProperty("Range", "bytes=" + 0 + "-");
conn.setConnectTimeout(mConnectTimeOut);
@ -133,7 +133,11 @@ class HttpFileInfoThread implements Runnable {
mTaskEntity.setSupportBP(true);
end = true;
} else if (code == HttpURLConnection.HTTP_OK) {
if (conn.getHeaderField("Content-Type").equals("text/html")) {
String contentType = conn.getHeaderField("Content-Type");
if (TextUtils.isEmpty(contentType)) {
return;
}
if (contentType.equals("text/html")) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(ConnectionHelp.convertInputStream(conn)));
StringBuilder sb = new StringBuilder();
@ -155,7 +159,8 @@ class HttpFileInfoThread implements Runnable {
failDownload("任务【" + mEntity.getUrl() + "】下载失败,错误码:404", true);
} else if (code == HttpURLConnection.HTTP_MOVED_TEMP
|| code == HttpURLConnection.HTTP_MOVED_PERM
|| code == HttpURLConnection.HTTP_SEE_OTHER) {
|| code == HttpURLConnection.HTTP_SEE_OTHER
|| code == 307) {
handleUrlReTurn(conn, conn.getHeaderField("Location"));
} else {
failDownload("任务【" + mEntity.getUrl() + "】下载失败,错误码:" + code, true);

@ -26,11 +26,16 @@ import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.BufferedRandomAccessFile;
import com.arialyy.aria.util.CommonUtil;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
/**
* Created by lyy on 2017/1/18.
@ -38,10 +43,6 @@ import java.net.URL;
*/
final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEntity> {
private final String TAG = "HttpThreadTask";
/**
* 2M的动态长度
*/
private final int LEN_INTERVAL = 1024 * 1024 * 2;
private boolean isOpenDynamicFile;
HttpThreadTask(StateConstance constance, IDownloadListener listener,
@ -52,7 +53,7 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
mReadTimeOut = manager.getDownloadConfig().getIOTimeOut();
mBufSize = manager.getDownloadConfig().getBuffSize();
isNotNetRetry = manager.getDownloadConfig().isNotNetRetry();
isOpenDynamicFile = STATE.TASK_RECORD.isOpenDynamicFile;
isOpenDynamicFile = STATE.isOpenDynamicFile;
setMaxSpeed(manager.getDownloadConfig().getMaxSpeed());
}
@ -64,47 +65,44 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
mChildCurrentLocation = mConfig.START_LOCATION;
try {
URL url = new URL(CommonUtil.convertUrl(mConfig.URL));
conn = ConnectionHelp.handleConnection(url);
conn = ConnectionHelp.handleConnection(url, mTaskEntity);
if (mConfig.SUPPORT_BP) {
ALog.d(TAG, "任务【"
+ mConfig.TEMP_FILE.getName()
+ "】线程__"
+ mConfig.THREAD_ID
+ "__开始下载【开始位置 : "
+ mConfig.START_LOCATION
+ ",结束位置:"
+ mConfig.END_LOCATION
+ "】");
ALog.d(TAG,
String.format("任务【%s】线程__%s__开始下载【开始位置 : %s,结束位置:%s】", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID, mConfig.START_LOCATION, mConfig.END_LOCATION));
//在头里面请求下载开始位置和结束位置
conn.setRequestProperty("Range",
"bytes=" + mConfig.START_LOCATION + "-" + (mConfig.END_LOCATION - 1));
String.format("bytes=%s-%s", mConfig.START_LOCATION, (mConfig.END_LOCATION - 1)));
} else {
ALog.w(TAG, "该下载不支持断点");
}
conn = ConnectionHelp.setConnectParam(mConfig.TASK_ENTITY, conn);
conn.setConnectTimeout(mConnectTimeOut);
conn.setReadTimeout(mReadTimeOut); //设置读取流的等待时间,必须设置该参数
conn.connect();
is = new BufferedInputStream(ConnectionHelp.convertInputStream(conn));
//创建可设置位置的文件
file = new BufferedRandomAccessFile(mConfig.TEMP_FILE, "rwd", mBufSize);
//设置每条线程写入文件的位置
file.seek(mConfig.START_LOCATION);
if (mTaskEntity.isChunked()) {
readChunk(is, file);
if (isOpenDynamicFile) {
readDynamicFile(is);
} else {
readNormal(is, file);
//创建可设置位置的文件
file = new BufferedRandomAccessFile(mConfig.TEMP_FILE, "rwd", mBufSize);
//设置每条线程写入文件的位置
file.seek(mConfig.START_LOCATION);
if (mTaskEntity.isChunked()) {
readChunk(is, file);
} else {
readNormal(is, file);
}
}
if (STATE.isCancel || STATE.isStop) {
if (isBreak()) {
return;
}
handleComplete();
} catch (MalformedURLException e) {
fail(mChildCurrentLocation, "下载链接异常", e);
} catch (IOException e) {
fail(mChildCurrentLocation, "下载失败【" + mConfig.URL + "】", e);
fail(mChildCurrentLocation, String.format("下载失败【%s】", mConfig.URL), e);
} catch (Exception e) {
fail(mChildCurrentLocation, "获取流失败", e);
} finally {
@ -124,6 +122,52 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
}
}
/**
* 动态长度文件读取方式
*/
private void readDynamicFile(InputStream is) {
FileOutputStream fos = null;
FileChannel foc = null;
ReadableByteChannel fic = null;
try {
int len;
fos = new FileOutputStream(mConfig.TEMP_FILE, true);
foc = fos.getChannel();
fic = Channels.newChannel(is);
ByteBuffer bf = ByteBuffer.allocate(mBufSize);
while ((len = fic.read(bf)) != -1) {
if (isBreak()) {
break;
}
if (mSleepTime > 0) {
Thread.sleep(mSleepTime);
}
bf.flip();
foc.write(bf);
bf.compact();
progress(len);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
fail(mChildCurrentLocation, String.format("下载失败【%s】", mConfig.URL), e);
} finally {
try {
if (fos != null) {
fos.close();
}
if (foc != null) {
foc.close();
}
if (fic != null) {
fic.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读取chunk模式的文件流
*
@ -142,17 +186,12 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
byte[] buffer = new byte[mBufSize];
int len;
while ((len = is.read(buffer)) != -1) {
if (STATE.isCancel || STATE.isStop) {
if (isBreak()) {
break;
}
if (mSleepTime > 0) {
Thread.sleep(mSleepTime);
}
if (isOpenDynamicFile) {
file.setLength(
STATE.CURRENT_LOCATION + LEN_INTERVAL < mEntity.getFileSize() ? STATE.CURRENT_LOCATION
+ LEN_INTERVAL : mEntity.getFileSize());
}
file.write(buffer, 0, len);
progress(len);
}
@ -160,15 +199,14 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
/**
* 处理完成配置文件的更新或事件回调
*
* @throws IOException
*/
private void handleComplete() throws IOException {
private void handleComplete() {
//支持断点的处理
if (mConfig.SUPPORT_BP) {
if (mChildCurrentLocation == mConfig.END_LOCATION) {
ALog.i(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】线程__" + mConfig.THREAD_ID + "__下载完毕");
writeConfig(true, 1);
ALog.i(TAG,
String.format("任务【%s】线程__%s__下载完毕", mConfig.TEMP_FILE.getName(), mConfig.THREAD_ID));
writeConfig(true, mConfig.END_LOCATION);
STATE.COMPLETE_THREAD_NUM++;
if (STATE.isComplete()) {
STATE.TASK_RECORD.deleteData();
@ -188,8 +226,4 @@ final class HttpThreadTask extends AbsThreadTask<DownloadEntity, DownloadTaskEnt
mListener.onComplete();
}
}
@Override protected String getTaskType() {
return "HTTP_DOWNLOAD";
}
}

@ -50,6 +50,9 @@ public abstract class AbsEntity extends DbEntity implements IEntity, Parcelable
*/
private String convertFileSize;
/**
* 任务状态{@link IEntity}
*/
private int state = STATE_WAIT;
/**
* 当前下载进度

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.inf;
import android.support.annotation.CheckResult;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.command.ICmd;
@ -34,7 +35,7 @@ import java.util.List;
*/
public abstract class AbsTarget<TARGET extends AbsTarget, ENTITY extends AbsEntity, TASK_ENTITY extends AbsTaskEntity>
implements ITarget<TARGET> {
protected String TAG = "";
protected String TAG ;
protected ENTITY mEntity;
protected TASK_ENTITY mTaskEntity;
protected String mTargetName;
@ -48,6 +49,7 @@ public abstract class AbsTarget<TARGET extends AbsTarget, ENTITY extends AbsEnti
* 注意如果在后续方法调用链中没有调用 {@link #start()}{@link #stop()}{@link #cancel()}{@link #resume()}
* 等操作任务的方法那么你需要调用{@link #save()}才能将修改保存到数据库
*/
@CheckResult(suggest = "after use #start()、#stop()、#cancel()、#resume()、#save()?")
public TARGET resetState() {
mTaskEntity.getEntity().setState(IEntity.STATE_WAIT);
mTaskEntity.setRefreshInfo(true);
@ -102,12 +104,13 @@ public abstract class AbsTarget<TARGET extends AbsTarget, ENTITY extends AbsEnti
*
* @param str 扩展数据
*/
@CheckResult(suggest = "after use #start()、#stop()、#cancel()、#resume()、#save()?")
public TARGET setExtendField(String str) {
if (TextUtils.isEmpty(str)) return (TARGET) this;
if (TextUtils.isEmpty(mEntity.getStr()) || !mEntity.getStr().equals(str)) {
mEntity.setStr(str);
} else {
ALog.e(TAG, "设置扩展字段失败,扩展字段为null");
ALog.e(TAG, "设置扩展字段失败,扩展字段为一致");
}
return (TARGET) this;

@ -19,6 +19,7 @@ import com.arialyy.aria.core.FtpUrlEntity;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.orm.annotation.Ignore;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;
@ -124,6 +125,8 @@ public abstract class AbsTaskEntity<ENTITY extends AbsEntity> extends DbEntity {
*/
private int code;
@Ignore private Proxy proxy;
public abstract ENTITY getEntity();
/**
@ -135,6 +138,14 @@ public abstract class AbsTaskEntity<ENTITY extends AbsEntity> extends DbEntity {
return getEntity().getState();
}
public Proxy getProxy() {
return proxy;
}
public void setProxy(Proxy proxy) {
this.proxy = proxy;
}
public abstract String getKey();
public abstract void setKey(String key);

@ -15,6 +15,8 @@
*/
package com.arialyy.aria.core.inf;
import android.support.annotation.CheckResult;
/**
* Created by laoyuyu on 2018/3/9.
*/
@ -22,6 +24,7 @@ public interface IFtpTarget<TARGET extends ITarget> {
/**
* 设置字符编码
*/
@CheckResult
TARGET charSet(String charSet);
/**
@ -30,6 +33,7 @@ public interface IFtpTarget<TARGET extends ITarget> {
* @param userName ftp用户名
* @param password ftp用户密码
*/
@CheckResult
TARGET login(String userName, String password);
/**
@ -39,5 +43,6 @@ public interface IFtpTarget<TARGET extends ITarget> {
* @param password ftp用户密码
* @param account ftp账号
*/
@CheckResult
TARGET login(String userName, String password, String account);
}

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.inf;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.core.download.DownloadEntity;
@ -33,6 +34,7 @@ public interface IHttpHeaderTarget<TARGET extends ITarget> {
* @param key header对应的key
* @param value header对应的value
*/
@CheckResult
TARGET addHeader(@NonNull String key, @NonNull String value);
/**
@ -41,6 +43,7 @@ public interface IHttpHeaderTarget<TARGET extends ITarget> {
*
* @param headers 一组http header数据
*/
@CheckResult
TARGET addHeaders(Map<String, String> headers);
/**
@ -48,5 +51,6 @@ public interface IHttpHeaderTarget<TARGET extends ITarget> {
*
* @param requestEnum {@link RequestEnum}
*/
@CheckResult
TARGET setRequestMode(RequestEnum requestEnum);
}

@ -23,6 +23,7 @@ import com.arialyy.aria.core.download.wrapper.DGEWrapper;
import com.arialyy.aria.core.download.wrapper.DGTEWrapper;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.CommonUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@ -156,10 +157,12 @@ class DGTEFactory implements IGTEFactory<DownloadGroupEntity, DownloadGroupTaskE
private List<DownloadEntity> createSubTask(String groupName, List<String> urls) {
List<DownloadEntity> list = new ArrayList<>();
for (int i = 0, len = urls.size(); i < len; i++) {
String url = urls.get(i);
DownloadEntity entity = new DownloadEntity();
entity.setUrl(urls.get(i));
entity.setUrl(url);
entity.setDownloadPath(groupName + "_" + i);
entity.setFileName(groupName + "_" + i);
int lastIndex = url.lastIndexOf(File.separator);
entity.setFileName(url.substring(lastIndex + 1, url.length()));
entity.setGroupName(groupName);
entity.setGroupChild(true);
list.add(entity);

@ -165,7 +165,7 @@ public class TEManager {
/**
* 从缓存中获取单任务实体如果任务实体不存在则创建任务实体
*
* @return 创建失败返回null
* @return 创建失败返回null成功返回{@link DownloadTaskEntity}或者{@link UploadTaskEntity}
*/
public <TE extends AbsTaskEntity> TE getTEntity(Class<TE> clazz, String key) {
final Lock lock = this.lock;
@ -185,7 +185,7 @@ public class TEManager {
/**
* 从缓存中获取FTP文件夹任务实体如果任务实体不存在则创建任务实体
*
* @return 创建失败返回null
* @return 创建失败返回null成功返回{@link DownloadTaskEntity}
*/
public <TE extends AbsTaskEntity> TE getFDTEntity(Class<TE> clazz, String key) {
final Lock lock = this.lock;
@ -204,9 +204,10 @@ public class TEManager {
/**
* 从缓存中获取HTTP任务组的任务实体如果任务实体不存在则创建任务实体
* 获取{}
*
* @param urls HTTP任务组的子任务下载地址列表
* @return 地址列表为null或创建实体失败返回null
* @return 地址列表为null或创建实体失败返回null成功返回{@link DownloadGroupTaskEntity}
*/
public <TE extends AbsTaskEntity> TE getGTEntity(Class<TE> clazz, List<String> urls) {
if (urls == null || urls.isEmpty()) {

@ -46,16 +46,6 @@ abstract class AbsTaskQueue<TASK extends AbsTask, TASK_ENTITY extends AbsTaskEnt
return mExecutePool.getTask(key) != null;
}
@Override public void removeAllTask() {
for (String key : mExecutePool.getAllTask().keySet()) {
TASK task = mExecutePool.getAllTask().get(key);
if (task != null) task.cancel();
}
for (String key : mCachePool.getAllTask().keySet()) {
mCachePool.removeTask(key);
}
}
/**
* 恢复任务
* 如果执行队列任务未满则直接启动任务
@ -165,12 +155,14 @@ abstract class AbsTaskQueue<TASK extends AbsTask, TASK_ENTITY extends AbsTaskEnt
}
@Override public void stopTask(TASK task) {
if (!task.isRunning()) ALog.w(TAG, "停止任务【" + task.getTaskName() + "】失败,原因:已停止");
if (!task.isRunning()) {
ALog.w(TAG, String.format("停止任务【%s】失败,原因:已停止", task.getTaskName()));
}
if (mExecutePool.removeTask(task)) {
task.stop();
} else {
task.stop();
ALog.w(TAG, "删除任务【" + task.getTaskName() + "】失败,原因:执行队列中没有该任务");
ALog.w(TAG, String.format("删除任务【%s】失败,原因:执行队列中没有该任务", task.getTaskName()));
}
}
@ -178,13 +170,13 @@ abstract class AbsTaskQueue<TASK extends AbsTask, TASK_ENTITY extends AbsTaskEnt
//TEManager.getInstance().removeTEntity(key);
TASK task = mExecutePool.getTask(key);
if (task != null) {
ALog.d(TAG,
"从执行池删除任务【" + task.getTaskName() + "】" + (mExecutePool.removeTask(task) ? "成功" : "失败"));
ALog.d(TAG, String.format("从执行池删除任务【%s】%s", task.getTaskName(),
(mExecutePool.removeTask(task) ? "成功" : "失败")));
}
task = mCachePool.getTask(key);
if (task != null) {
ALog.d(TAG,
"从缓存池删除任务【" + task.getTaskName() + "】" + (mCachePool.removeTask(task) ? "成功" : "失败"));
ALog.d(TAG, String.format("从缓存池删除任务【%s】%s", task.getTaskName(),
(mCachePool.removeTask(task) ? "成功" : "失败")));
}
}
@ -201,7 +193,7 @@ abstract class AbsTaskQueue<TASK extends AbsTask, TASK_ENTITY extends AbsTaskEnt
task.start();
} else {
task.stop();
ALog.e(TAG, "任务【" + task.getTaskName() + "】重试失败,原因:任务没有完全停止,");
ALog.e(TAG, String.format("任务【%s】重试失败,原因:任务没有完全停止", task.getTaskName()));
}
}

@ -52,11 +52,6 @@ public interface ITaskQueue<TASK extends AbsTask, TASK_ENTITY extends AbsTaskEnt
*/
void stopAllTask();
/**
* 删除所有任务
*/
void removeAllTask();
/**
* 开始任务
*

@ -17,6 +17,7 @@ package com.arialyy.aria.core.scheduler;
import android.os.CountDownTimer;
import android.os.Message;
import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.download.DownloadGroupTask;
import com.arialyy.aria.core.download.DownloadTask;
@ -157,7 +158,7 @@ abstract class AbsSchedulers<TASK_ENTITY extends AbsTaskEntity, TASK extends Abs
}
/**
* 处理普通任务事件
* 处理普通任务和任务组的事件
*/
private void handleNormalEvent(TASK task, int what) {
switch (what) {
@ -292,7 +293,7 @@ abstract class AbsSchedulers<TASK_ENTITY extends AbsTaskEntity, TASK extends Abs
@Override public void onFinish() {
AbsEntity entity = task.getTaskEntity().getEntity();
if (entity.getFailNum() <= reTryNum) {
ALog.d(TAG, "任务【" + task.getTaskName() + "】开始重试");
ALog.d(TAG, String.format("任务【%s】开始重试", task.getTaskName()));
TASK task = mQueue.getTask(entity.getKey());
mQueue.reTryStart(task);
} else {
@ -311,7 +312,9 @@ abstract class AbsSchedulers<TASK_ENTITY extends AbsTaskEntity, TASK extends Abs
private void startNextTask() {
TASK newTask = mQueue.getNextTask();
if (newTask == null) {
ALog.i(TAG, "没有下一任务");
if (mQueue.getCurrentExePoolNum() == 0) {
ALog.i(TAG, "没有下一任务");
}
return;
}
if (newTask.getState() == IEntity.STATE_WAIT) {

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.upload;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.arialyy.aria.core.manager.TEManager;
@ -44,6 +45,7 @@ abstract class BaseNormalTarget<TARGET extends AbsUploadTarget>
*
* @param uploadUrl 上传路径
*/
@CheckResult
public TARGET setUploadUrl(@NonNull String uploadUrl) {
mTempUrl = uploadUrl;
return (TARGET) this;

@ -144,15 +144,16 @@ class BaseUListener<ENTITY extends AbsEntity, TASK_ENTITY extends AbsTaskEntity<
mEntity.setState(state);
mEntity.setComplete(state == IEntity.STATE_COMPLETE);
if (state == IEntity.STATE_CANCEL) {
if (mEntity instanceof AbsNormalEntity) {
if (mEntity instanceof UploadEntity) {
TaskRecord record =
DbEntity.findFirst(TaskRecord.class, "TaskRecord.filePath=?", mTaskEntity.getKey());
if (record != null) {
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), (AbsNormalEntity) mEntity);
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), (UploadEntity) mEntity);
}
} else if (mEntity instanceof AbsGroupEntity) {
CommonUtil.delGroupTaskRecord(mTaskEntity.isRemoveFile(), ((AbsGroupEntity) mEntity));
}
//else if (mEntity instanceof AbsGroupEntity) {
// CommonUtil.delGroupTaskRecord(mTaskEntity.isRemoveFile(), ((AbsGroupEntity) mEntity));
//}
return;
} else if (mEntity.isComplete()) {
mEntity.setCompleteTime(System.currentTimeMillis());

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.upload;
import android.support.annotation.CheckResult;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.command.normal.NormalCmdFactory;
import com.arialyy.aria.core.delegate.FtpDelegate;
@ -69,6 +70,7 @@ public class FtpUploadTarget extends BaseNormalTarget<FtpUploadTarget>
return true;
}
@CheckResult
@Override public FtpUploadTarget charSet(String charSet) {
return mDelegate.charSet(charSet);
}

@ -15,12 +15,13 @@
*/
package com.arialyy.aria.core.upload;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.command.ICmd;
import com.arialyy.aria.core.command.normal.NormalCmdFactory;
import com.arialyy.aria.core.common.ProxyHelper;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.AbsReceiver;
import com.arialyy.aria.core.scheduler.UploadSchedulers;
import com.arialyy.aria.orm.DbEntity;
@ -41,6 +42,7 @@ public class UploadReceiver extends AbsReceiver<UploadEntity> {
*
* @param filePath 文件路径
*/
@CheckResult
public UploadTarget load(@NonNull String filePath) {
CheckUtil.checkUploadPath(filePath);
return new UploadTarget(filePath, targetName);
@ -51,6 +53,7 @@ public class UploadReceiver extends AbsReceiver<UploadEntity> {
*
* @param filePath 文件路径
*/
@CheckResult
public FtpUploadTarget loadFtp(@NonNull String filePath) {
CheckUtil.checkUploadPath(filePath);
return new FtpUploadTarget(filePath, targetName);
@ -58,8 +61,12 @@ public class UploadReceiver extends AbsReceiver<UploadEntity> {
/**
* 通过上传路径获取上传实体
* 如果任务不存在方便null
*/
public UploadEntity getUploadEntity(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
return DbEntity.findFirst(UploadEntity.class, "filePath=?", filePath);
}
@ -95,7 +102,6 @@ public class UploadReceiver extends AbsReceiver<UploadEntity> {
"isGroupChild=? and isComplete=?", "false", "true");
}
@Override public void stopAllTask() {
AriaManager.getInstance(AriaManager.APP)
.setCmd(NormalCmdFactory.getInstance()
@ -129,13 +135,12 @@ public class UploadReceiver extends AbsReceiver<UploadEntity> {
/**
* 将当前类注册到Aria
*/
public UploadReceiver register() {
public void register() {
String className = obj.getClass().getName();
Set<String> cCounter = ProxyHelper.getInstance().uploadCounter;
if (cCounter != null && cCounter.contains(className)) {
UploadSchedulers.getInstance().register(obj);
}
return this;
}
/**

@ -15,6 +15,7 @@
*/
package com.arialyy.aria.core.upload;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.core.delegate.HttpHeaderDelegate;
@ -47,6 +48,7 @@ public class UploadTarget extends BaseNormalTarget<UploadTarget>
/**
* 设置userAgent
*/
@CheckResult
public UploadTarget setUserAngent(@NonNull String userAgent) {
mTaskEntity.setUserAgent(userAgent);
return this;
@ -57,6 +59,7 @@ public class UploadTarget extends BaseNormalTarget<UploadTarget>
*
* @param attachment 附件key
*/
@CheckResult
public UploadTarget setAttachment(@NonNull String attachment) {
mTaskEntity.setAttachment(attachment);
return this;
@ -67,19 +70,23 @@ public class UploadTarget extends BaseNormalTarget<UploadTarget>
*
* @param contentType tipmultipart/form-data
*/
@CheckResult
public UploadTarget setContentType(String contentType) {
mTaskEntity.setContentType(contentType);
return this;
}
@CheckResult
@Override public UploadTarget addHeader(@NonNull String key, @NonNull String value) {
return mDelegate.addHeader(key, value);
}
@CheckResult
@Override public UploadTarget addHeaders(Map<String, String> headers) {
return mDelegate.addHeaders(headers);
}
@CheckResult
@Override public UploadTarget setRequestMode(RequestEnum requestEnum) {
return mDelegate.setRequestMode(requestEnum);
}

@ -54,15 +54,9 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
FTPClient client = null;
BufferedRandomAccessFile file = null;
try {
ALog.d(TAG, "任务【"
+ mConfig.TEMP_FILE.getName()
+ "】线程__"
+ mConfig.THREAD_ID
+ "__开始上传【开始位置 : "
+ mConfig.START_LOCATION
+ ",结束位置:"
+ mConfig.END_LOCATION
+ "】");
ALog.d(TAG,
String.format("任务【%s】线程__%s__开始上传【开始位置 : %s,结束位置:%s】", mConfig.TEMP_FILE.getName(),
mConfig.THREAD_ID, mConfig.START_LOCATION, mConfig.END_LOCATION));
client = createClient();
if (client == null) return;
initPath();
@ -82,9 +76,12 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
file.seek(mConfig.START_LOCATION);
}
upload(client, file);
if (STATE.isCancel || STATE.isStop) return;
ALog.i(TAG, "任务【" + mConfig.TEMP_FILE.getName() + "】线程__" + mConfig.THREAD_ID + "__上传完毕");
writeConfig(true, 1);
if (isBreak()) {
return;
}
ALog.i(TAG,
String.format("任务【%s】线程__%s__上传完毕", mConfig.TEMP_FILE.getName(), mConfig.THREAD_ID));
writeConfig(true, mConfig.END_LOCATION);
STATE.COMPLETE_THREAD_NUM++;
if (STATE.isComplete()) {
STATE.TASK_RECORD.deleteData();
@ -96,7 +93,7 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
mListener.onFail(false);
}
} catch (IOException e) {
fail(mChildCurrentLocation, "上传失败【" + mConfig.URL + "】", e);
fail(mChildCurrentLocation, String.format("上传失败【%s】", mConfig.URL), e);
} catch (Exception e) {
fail(mChildCurrentLocation, "获取流失败", e);
} finally {
@ -125,13 +122,13 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
throws IOException {
try {
ALog.d(TAG, "remotePath【" + remotePath + "】");
ALog.d(TAG, String.format("remotePath【%s】", remotePath));
client.storeFile(remotePath, new FtpFISAdapter(bis), new OnFtpInputStreamListener() {
boolean isStoped = false;
@Override public void onFtpInputStream(FTPClient client, long totalBytesTransferred,
int bytesTransferred, long streamSize) {
if ((STATE.isCancel || STATE.isStop) && !isStoped) {
if (isBreak() && !isStoped) {
try {
isStoped = true;
client.abor();
@ -153,7 +150,8 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
if (reply != FTPReply.TRANSFER_ABORTED) {
fail(mChildCurrentLocation, "上传文件错误,错误码为:" + reply + ",msg:" + client.getReplyString(),
fail(mChildCurrentLocation,
String.format("上传文件错误,错误码为:%s,msg:%s", reply, client.getReplyString()),
null);
}
if (client.isConnected()) {
@ -161,8 +159,4 @@ class FtpThreadTask extends AbsFtpThreadTask<UploadEntity, UploadTaskEntity> {
}
}
}
@Override protected String getTaskType() {
return "FTP_UPLOAD";
}
}

@ -62,7 +62,7 @@ class HttpThreadTask extends AbsThreadTask<UploadEntity, UploadTaskEntity> {
@Override public void run() {
File uploadFile = new File(mEntity.getFilePath());
if (!uploadFile.exists()) {
ALog.e(TAG, "【" + mEntity.getFilePath() + "】,文件不存在。");
ALog.e(TAG, String.format("【%s】,文件不存在。", mEntity.getFilePath()));
fail();
return;
}
@ -212,8 +212,4 @@ class HttpThreadTask extends AbsThreadTask<UploadEntity, UploadTaskEntity> {
mOutputStream.close();
return response.toString();
}
@Override protected String getTaskType() {
return "HTTP_UPLOAD";
}
}

@ -48,7 +48,7 @@ abstract class AbsDelegate {
* @param type {@link DelegateWrapper}
*/
static void print(int type, String sql) {
if (!ALog.DEBUG) {
if (ALog.DEBUG) {
return;
}
String str = "";

@ -30,6 +30,7 @@ import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -217,8 +218,8 @@ class DelegateFind extends AbsDelegate {
}
List<T> wrappers = new ArrayList<>();
Map<Object, P> tempParent = new WeakHashMap<>(); // 所有父表元素,key为父表主键的值
Map<Object, List<C>> tempChild = new WeakHashMap<>(); // 所有的字表元素,key为父表主键的值
Map<Object, P> tempParent = new LinkedHashMap<>(); // 所有父表元素,key为父表主键的值
Map<Object, List<C>> tempChild = new LinkedHashMap<>(); // 所有的字表元素,key为父表主键的值
Object old = null;
while (cursor.moveToNext()) {

@ -117,6 +117,9 @@ public class ALog {
* 将异常信息转换为字符串
*/
public static String getExceptionString(Throwable ex) {
if (ex == null) {
return "";
}
StringBuilder err = new StringBuilder();
err.append("ExceptionDetailed:\n");
err.append("====================Exception Info====================\n");

@ -23,6 +23,7 @@ import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.FtpUrlEntity;
import com.arialyy.aria.core.command.ICmd;
@ -33,7 +34,6 @@ import com.arialyy.aria.core.command.normal.NormalCmdFactory;
import com.arialyy.aria.core.common.TaskRecord;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadGroupEntity;
import com.arialyy.aria.core.inf.AbsGroupEntity;
import com.arialyy.aria.core.inf.AbsGroupTaskEntity;
import com.arialyy.aria.core.inf.AbsNormalEntity;
import com.arialyy.aria.core.inf.AbsTaskEntity;
@ -53,17 +53,14 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -77,34 +74,55 @@ public class CommonUtil {
/**
* 获取某包下所有类
*
* @param packageName
* @param className 过滤的类
* @return 类的完整名称
*/
public static List<String> getClassName(Context context, String packageName) {
public static List<String> getClassName(Context context, String className) {
List<String> classNameList = new ArrayList<>();
try {
String pPath = context.getPackageCodePath();
File dir = new File(pPath).getParentFile();
String pPath = context.getPackageCodePath();
File dir = new File(pPath).getParentFile();
String[] paths = dir.list();
if (paths == null) {
classNameList.addAll(getPkgClassName(pPath, className));
} else {
String dPath = dir.getPath();
for (String path : dir.list()) {
String fPath = dPath + "/" + path;
if (!fPath.endsWith(".apk")) {
continue;
}
DexFile df = new DexFile(fPath);//通过DexFile查找当前的APK中可执行文件
Enumeration<String> enumeration = df.entries();//获取df中的元素 这里包含了所有可执行的类名 该类名包含了包名+类名的方式
while (enumeration.hasMoreElements()) {//遍历
String className = enumeration.nextElement();
if (className.contains(packageName)) {//在当前所有可执行的类里面查找包含有该包名的所有类
classNameList.add(className);
}
classNameList.addAll(getPkgClassName(fPath, className));
}
}
return classNameList;
}
/**
* 获取指定包名下的所有类
*
* @param path dex路径
* @param filterClass 需要过滤的类
*/
public static List<String> getPkgClassName(String path, String filterClass) {
List<String> list = new ArrayList<>();
try {
DexFile df = new DexFile(path);//通过DexFile查找当前的APK中可执行文件
Enumeration<String> enumeration = df.entries();//获取df中的元素 这里包含了所有可执行的类名 该类名包含了包名+类名的方式
while (enumeration.hasMoreElements()) {
String _className = enumeration.nextElement();
if (!_className.contains(filterClass)) {
continue;
}
if (_className.contains(filterClass)) {
list.add(_className);
}
df.close();
}
df.close();
} catch (IOException e) {
e.printStackTrace();
}
return classNameList;
return list;
}
/**
@ -246,53 +264,30 @@ public class CommonUtil {
* @param url 输入的url{@code String url = "ftp://z:z@dygod18.com:21211/[电影天堂www.dy2018.com]猩球崛起3:终极之战BD国英双语中英双字.mkv";}
*/
public static FtpUrlEntity getFtpUrlInfo(String url) {
Uri uri = Uri.parse(url);
String userInfo = uri.getUserInfo(), remotePath = uri.getPath();
ALog.d(TAG,
String.format("scheme = %s, user = %s, host = %s, port = %s, path = %s", uri.getScheme(),
userInfo, uri.getHost(), uri.getPort(), remotePath));
FtpUrlEntity entity = new FtpUrlEntity();
entity.url = url;
//String regex = "(\\w+)://(.*):(\\d*)/(.*)";
String regex = Regular.REG_FTP_URL;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(url);
if (m.find() && m.groupCount() > 0) {
entity.protocol = m.group(1);
String str = m.group(2);
if (str.contains("@")) {
entity.needLogin = true;
//String hostReg = "(\\w+):?(\\w+)?@(.*)";
String hostReg = Regular.REG_FTP_HOST_NAME;
Pattern hp = Pattern.compile(hostReg);
Matcher hm = hp.matcher(str);
if (hm.find() && hm.groupCount() > 0) {
entity.user = hm.group(1);
entity.password = TextUtils.isEmpty(hm.group(2)) ? "" : hm.group(2);
entity.hostName = hm.group(3);
}
entity.hostName = uri.getHost();
entity.port = uri.getPort() == -1 ? "21" : String.valueOf(uri.getPort());
if (!TextUtils.isEmpty(userInfo)) {
String[] temp = userInfo.split(":");
if (temp.length == 2) {
entity.user = temp[0];
entity.password = temp[1];
} else {
entity.hostName = str;
entity.user = userInfo;
}
entity.port = m.group(3);
//entity.remotePath = TextUtils.isEmpty(m.group(4)) ? "/" : "/" + m.group(4);
entity.remotePath = TextUtils.isEmpty(m.group(4)) ? "/" : m.group(4);
}
entity.remotePath = TextUtils.isEmpty(remotePath) ? "/" : remotePath;
return entity;
}
/**
* 通过url获取FTP文件的remotePath
*
* @return remotePath如果没有找到返回""
*/
public static String getRemotePath(String url) {
String remotePath = null;
String regex = Regular.REG_FTP_URL;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(url);
if (m.find() && m.groupCount() > 0) {
return TextUtils.isEmpty(m.group(4)) ? "" : "/" + m.group(4);
}
ALog.w(TAG, "链接【" + url + "】没有找到remotePath");
return "";
}
/**
* 转换Url
*
@ -300,25 +295,27 @@ public class CommonUtil {
* @return 转换后的地址
*/
public static String convertUrl(String url) {
if (hasDoubleCharacter(url)) {
//预先处理空格,URLEncoder只会把空格转换为+
url = url.replaceAll(" ", "%20");
//匹配双字节字符(包括汉字在内)
String regex = Regular.REG_DOUBLE_CHAR_AND_SPACE;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(url);
Set<String> strs = new HashSet<>();
while (m.find()) {
strs.add(m.group());
}
try {
for (String str : strs) {
url = url.replaceAll(str, URLEncoder.encode(str, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Uri uri = Uri.parse(url);
url = uri.toString();
//if (hasDoubleCharacter(url)) {
// //预先处理空格,URLEncoder只会把空格转换为+
// url = url.replaceAll(" ", "%20");
// //匹配双字节字符(包括汉字在内)
// String regex = Regular.REG_DOUBLE_CHAR_AND_SPACE;
// Pattern p = Pattern.compile(regex);
// Matcher m = p.matcher(url);
// Set<String> strs = new HashSet<>();
// while (m.find()) {
// strs.add(m.group());
// }
// try {
// for (String str : strs) {
// url = url.replaceAll(str, URLEncoder.encode(str, "UTF-8"));
// }
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//}
return url;
}
@ -399,33 +396,34 @@ public class CommonUtil {
* @param removeFile {@code true} 不仅删除任务数据库记录还会删除已经删除完成的文件
* {@code false}如果任务已经完成只删除任务数据库记录
*/
public static void delGroupTaskRecord(boolean removeFile, AbsGroupEntity groupEntity) {
public static void delGroupTaskRecord(boolean removeFile, DownloadGroupEntity groupEntity) {
if (groupEntity == null) {
ALog.e(TAG, "删除下载任务组记录失败,任务组实体为null");
return;
}
List<TaskRecord> records = DbEntity.findDatas(TaskRecord.class,
groupEntity instanceof DownloadGroupEntity ? "dGroupName=?" : "uGroupName=?",
groupEntity.getGroupName());
List<TaskRecord> records =
DbEntity.findDatas(TaskRecord.class, "dGroupName=?", groupEntity.getGroupName());
if (records == null || records.isEmpty()) {
ALog.w(TAG, "组任务记录删除失败,记录为null");
return;
} else {
for (TaskRecord tr : records) {
tr.deleteData();
}
}
for (TaskRecord tr : records) {
tr.deleteData();
List<DownloadEntity> subs = groupEntity.getSubEntities();
if (subs != null) {
for (DownloadEntity sub : subs) {
File file = new File(sub.getDownloadPath());
if (file.exists() && (removeFile || !sub.isComplete())) {
file.delete();
}
}
}
File dir = new File(groupEntity.getDirPath());
if (removeFile) {
if (dir.exists()) {
dir.delete();
}
} else {
if (!groupEntity.isComplete()) {
dir.delete();
}
if (dir.exists() && (removeFile || !groupEntity.isComplete())) {
dir.delete();
}
groupEntity.deleteData();
}
@ -436,8 +434,7 @@ public class CommonUtil {
* @param removeFile {@code true} 不仅删除任务数据库记录还会删除已经完成的文件
* {@code false}如果任务已经完成只删除任务数据库记录
*/
public static void delTaskRecord(TaskRecord record, boolean removeFile,
AbsNormalEntity dEntity) {
public static void delTaskRecord(TaskRecord record, boolean removeFile, AbsNormalEntity dEntity) {
if (dEntity == null) return;
File file;
if (dEntity instanceof DownloadEntity) {
@ -448,16 +445,8 @@ public class CommonUtil {
ALog.w(TAG, "删除记录失败,未知类型");
return;
}
if (removeFile) {
if (file.exists()) {
file.delete();
}
} else {
if (!dEntity.isComplete()) {
if (file.exists()) {
file.delete();
}
}
if (file.exists() && (removeFile || !dEntity.isComplete())) {
file.delete();
}
if (record != null) {
@ -889,14 +878,11 @@ public class CommonUtil {
ALog.w(TAG, "修改任务记录失败,新文件路径和旧文件路径一致");
return;
}
File oldFile = new File(oldPath);
if (!oldFile.exists()) {
ALog.w(TAG, "修改任务记录失败,文件【" + oldPath + "】不存在");
return;
}
TaskRecord record = DbHelper.getTaskRecord(oldPath);
if (record == null) {
ALog.w(TAG, "修改任务记录失败,文件【" + oldPath + "】对应的任务记录不存在");
if (new File(oldPath).exists()) {
ALog.w(TAG, "修改任务记录失败,文件【" + oldPath + "】对应的任务记录不存在");
}
return;
}
record.filePath = newPath;

@ -5,15 +5,6 @@ package com.arialyy.aria.util;
* 正则表达式
*/
public interface Regular {
/**
* ftp地址
*/
String REG_FTP_URL = "(\\w+)://(.*):(\\d*)/(.*)";
/**
* ftp主机用户密码分割
*/
String REG_FTP_HOST_NAME = "(\\w+):?(\\w+)?@(.*)";
/**
* 获取文件名

@ -1,4 +1,13 @@
## 开发日志
+ v_3.4.2
- fix bug https://github.com/AriaLyy/Aria/issues/248
- fix bug https://github.com/AriaLyy/Aria/issues/247
- fix bug https://github.com/AriaLyy/Aria/issues/250
- 添加任务判断是否存在的api
- 添加代理api
- 修复删除所有没有进出等待的问题
- 进度有时出错的问题
- FTP添加超时处理
+ v_3.4.1
- 移除记录配置文件,改用数据库记录任务记录
- 上传配置添加io超时时间、缓存大小配置

@ -30,8 +30,8 @@ Aria有以下特点:
[![Download](https://api.bintray.com/packages/arialyy/maven/AriaApi/images/download.svg)](https://bintray.com/arialyy/maven/AriaApi/_latestVersion)
[![Download](https://api.bintray.com/packages/arialyy/maven/AriaCompiler/images/download.svg)](https://bintray.com/arialyy/maven/AriaCompiler/_latestVersion)
```java
compile 'com.arialyy.aria:aria-core:3.4.1'
annotationProcessor 'com.arialyy.aria:aria-compiler:3.4.1'
compile 'com.arialyy.aria:aria-core:3.4.2'
annotationProcessor 'com.arialyy.aria:aria-compiler:3.4.2'
```
如果出现android support,请将 `compile 'com.arialyy.aria:aria-core:<last-version>'`替换为
```
@ -99,13 +99,15 @@ protected void onCreate(Bundle savedInstanceState) {
### 版本日志
+ v_3.4.1
- 移除记录配置文件,改用数据库记录任务记录
- 上传配置添加io超时时间、缓存大小配置
- 添加没有网络也会重试的开关
- 修复多次删除记录的bug
- 文件长度现在可动态增加,详情见 https://aria.laoyuyu.me/aria_doc/start/config.html
- 修复多module同时引用Aria导致打正式包出错的问题 https://github.com/AriaLyy/Aria/issues/240
+ v_3.4.2
- fix bug https://github.com/AriaLyy/Aria/issues/248
- fix bug https://github.com/AriaLyy/Aria/issues/247
- fix bug https://github.com/AriaLyy/Aria/issues/250
- 添加任务判断是否存在的api
- 添加代理api
- 修复删除所有没有进出等待的问题
- 进度有时出错的问题
- FTP添加超时处理
[更多版本记录](https://github.com/AriaLyy/Aria/blob/master/DEV_LOG.md)
@ -126,7 +128,7 @@ protected void onCreate(Bundle savedInstanceState) {
## 其他
有任何问题,可以在[issues](https://github.com/AriaLyy/Aria/issues)给我留言反馈。</br>
在提交问题前,希望你已经查看过[wiki](https://github.com/AriaLyy/Aria/wiki)或搜索过[issues](https://github.com/AriaLyy/Aria/issues)。</br>
在提交问题前,希望你已经查看过[wiki](https://aria.laoyuyu.me/aria_doc/)或搜索过[issues](https://github.com/AriaLyy/Aria/issues)。</br>
***
License

@ -2,7 +2,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.arialyy.simple">
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
@ -14,11 +13,13 @@
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar">
<!--android:name=".test.TestActivity"-->
<!--android:name=".test.AnyRunActivity"-->
<!--android:name=".test.TestGroupActivity"-->
<!--android:name=".test.AnyRunActivity"-->
<!--android:name=".test.TestActivity"-->
<!--android:name=".download.group.DownloadGroupActivity"-->
<activity
android:name=".MainActivity"
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
@ -34,7 +35,7 @@
<activity android:name=".download.multi_download.MultiDownloadActivity"/>
<activity android:name=".download.HighestPriorityActivity"/>
<activity android:name=".test.TestMutilTaskSysDownload"/>
<activity android:name=".download.group.DownloadGroupActivity"/>
<!--<activity android:name=".download.group.DownloadGroupActivity"/>-->
<activity android:name=".download.FtpDownloadActivity"/>
<activity android:name=".download.group.FTPDirDownloadActivity"/>
<activity android:name=".upload.HttpUploadActivity"/>

@ -11,21 +11,21 @@
<!--注意,修改该配置文件中的属性会覆盖代码中所设置的属性-->
<download>
<!--是否开启动态文件,开启动态文件后初始化时将不占用磁盘空间,下载多少byte,占多少空间,效果见chrome的下载。-->
<!--注意:
1、使用该功能,将自动关闭多线程下载;
2、对于已经采用了多线程的任务,依然采用原来的下载方式;
3、原本参数是true,任务没下载完成,就参数改为false,那么没下载完成的任务还是会按照参数修改前的方式下载;只有新任务才会根据参数调用不同的下载方式。-->
<openDynamicFile value="true"/>
<!--断网的时候是否重试,true:断网也重试;false:断网不重试,直接走失败的回调-->
<notNetRetry value="true"/>
<!--设置下载线程,线程下载数改变后,新的下载任务才会生效,如果任务大小小于1m,该设置也不会生效-->
<threadNum value="3"/>
<!--设置下载线程数,下载线程数不能小于1
注意:
1、线程下载数改变后,新的下载任务才会生效;
2、如果任务大小小于1m,该设置不会生效;
3、从3.4.1开始,如果线程数为1,文件初始化时将不再预占用对应长度的空间,下载多少byte,则占多大的空间;
对于采用多线程的任务或旧任务,依然采用原来的文件空间占用方式;
-->
<threadNum value="1"/>
<!--设置下载队列最大任务数, 默认为2-->
<maxTaskNum value="2"/>
<maxTaskNum value="1"/>
<!--设置下载失败,重试次数,默认为10-->
<reTryNum value="2"/>

@ -37,11 +37,7 @@ import java.io.File;
public class FtpDownloadActivity extends BaseActivity<ActivityFtpDownloadBinding> {
//private final String URL = "ftp://192.168.1.9:21/下载/AriaPrj.zip";
//private final String URL = "ftp://182.92.180.213:21/video/572fed5c2ad48_1024.jpg";
<<<<<<< HEAD
private final String URL = "ftp://182.92.180.213:21/DATA/20180205/rar/1111.rar";
=======
private final String URL = "ftp://192.168.1.7:21/download//AriaPrj.zip";
>>>>>>> v_3.4
//private final String URL = "ftp://d:d@dygodj8.com:12311/咖啡风暴HD大陆公映意语中字[飘花www.piaohua.com].mp4";
@Override protected void init(Bundle savedInstanceState) {
@ -64,18 +60,13 @@ public class FtpDownloadActivity extends BaseActivity<ActivityFtpDownloadBinding
switch (view.getId()) {
case R.id.start:
Aria.download(this).loadFtp(URL, true)
<<<<<<< HEAD
.login("sxf", "B34VdGsJ")
//.login("lao", "123456")
.setDownloadPath("/mnt/sdcard/").start();
=======
//.login("sxf", "B34VdGsJ")
.login("lao", "123456")
.setFilePath("/mnt/sdcard/").start();
>>>>>>> v_3.4
break;
case R.id.stop:
Aria.download(this).loadFtp(URL).stop();
Aria.download(this).loadFtp(URL);
break;
case R.id.cancel:
Aria.download(this).loadFtp(URL).cancel();

@ -49,8 +49,9 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
//"http://58.210.9.131/tpk/sipgt//TDLYZTGH.tpk"; //chunked 下载
//"https://static.donguo.me//video/ip/course/pfys_1.mp4";
//"https://www.baidu.com/link?url=_LFCuTPtnzFxVJByJ504QymRywIA1Z_T5xUxe9ZLuxcGM0C_RcdpWyB1eGjbJC-e5wv5wAKM4WmLMAS5KeF6EZJHB8Va3YqZUiaErqK_pxm&wd=&eqid=e8583fe70002d126000000065a99f864";
"https://d.pcs.baidu.com/file/a02c89a2d479d4fd2756f3313d42491d?fid=4232431903-250528-1114369760340736&dstime=1525491372&rt=sh&sign=FDtAERVY-DCb740ccc5511e5e8fedcff06b081203-3C13vkOkuk4TqXvVYW05zj1K0ao%3D&expires=8h&chkv=1&chkbd=0&chkpc=et&dp-logid=8651730921842106225&dp-callid=0&r=165533013";
//"https://d.pcs.baidu.com/file/a02c89a2d479d4fd2756f3313d42491d?fid=4232431903-250528-1114369760340736&dstime=1525491372&rt=sh&sign=FDtAERVY-DCb740ccc5511e5e8fedcff06b081203-3C13vkOkuk4TqXvVYW05zj1K0ao%3D&expires=8h&chkv=1&chkbd=0&chkpc=et&dp-logid=8651730921842106225&dp-callid=0&r=165533013";
//"http://apk500.bce.baidu-mgame.com/game/67000/67734/20170622040827_oem_5502845.apk?r=1";
"https://dl.genymotion.com/releases/genymotion-2.12.1/genymotion-2.12.1-vbox.exe";
@Bind(R.id.start) Button mStart;
@Bind(R.id.stop) Button mStop;
@Bind(R.id.cancel) Button mCancel;
@ -238,8 +239,8 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
//.addHeader("Accept-Encoding", "gzip, deflate")
//.addHeader("DNT", "1")
//.addHeader("Cookie", "BAIDUID=648E5FF020CC69E8DD6F492D1068AAA9:FG=1; BIDUPSID=648E5FF020CC69E8DD6F492D1068AAA9; PSTM=1519099573; BD_UPN=12314753; locale=zh; BDSVRTM=0")
.useServerFileName(true)
.setRequestMode(RequestEnum.GET)
//.useServerFileName(true)
//.setRequestMode(RequestEnum.GET)
.setFilePath(Environment.getExternalStorageDirectory().getPath() + "/ggsg3.apk")
//.resetState()
.start();

@ -84,7 +84,7 @@ public class DownloadGroupActivity extends BaseActivity<ActivityDownloadGroupBin
.setDirPath(
Environment.getExternalStorageDirectory().getPath() + "/Download/group_test_3")
.setGroupAlias("任务组测试")
.setSubFileName(getModule(GroupModule.class).getSubName())
//.setSubFileName(getModule(GroupModule.class).getSubName())
//.setFileSize(32895492)
.start();
break;
@ -92,7 +92,8 @@ public class DownloadGroupActivity extends BaseActivity<ActivityDownloadGroupBin
Aria.download(this).load(mUrls).stop();
break;
case R.id.cancel:
Aria.download(this).load(mUrls).cancel(true);
//Aria.download(this).load(mUrls).cancel(true);
Aria.download(this).removeAllTask(true);
//mUrls = getModule(GroupModule.class).getUrls1();
//Aria.download(this)
// .load(mUrls)

@ -32,7 +32,7 @@ public class GroupModule extends BaseModule {
public List<String> getUrls() {
List<String> urls = new ArrayList<>();
String[] str = getContext().getResources().getStringArray(R.array.group_urls_1);
String[] str = getContext().getResources().getStringArray(R.array.group_url4);
Collections.addAll(urls, str);
return urls;
}

@ -297,7 +297,7 @@ public class DownloadAdapter extends AbsRVAdapter<AbsEntity, DownloadAdapter.Sim
Aria.download(getContext()).load((DownloadEntity) entity).start();
break;
case AbsTaskEntity.DG_HTTP:
Aria.download(getContext()).load((DownloadGroupEntity) entity).start();
Aria.download(getContext()).loadGroup((DownloadGroupEntity) entity).start();
break;
}
}
@ -314,7 +314,7 @@ public class DownloadAdapter extends AbsRVAdapter<AbsEntity, DownloadAdapter.Sim
Aria.download(getContext()).load((DownloadEntity) entity).stop();
break;
case AbsTaskEntity.DG_HTTP:
Aria.download(getContext()).load((DownloadGroupEntity) entity).stop();
Aria.download(getContext()).loadGroup((DownloadGroupEntity) entity).stop();
break;
}
}

@ -29,6 +29,7 @@ import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadGroupTask;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.inf.AbsEntity;
import com.arialyy.aria.util.ALog;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivityMultiDownloadBinding;
@ -115,6 +116,11 @@ public class MultiDownloadActivity extends BaseActivity<ActivityMultiDownloadBin
mAdapter.updateState(task.getEntity());
}
@DownloadGroup.onWait void groupTaskWait(DownloadGroupTask task) {
ALog.d(TAG, String.format("group【%s】wait", task.getTaskName()));
mAdapter.updateState(task.getEntity());
}
@DownloadGroup.onTaskResume void groupTaskResume(DownloadGroupTask task) {
mAdapter.updateState(task.getEntity());
}

@ -121,6 +121,7 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
@DownloadGroup.onTaskStop void groupTaskStop(DownloadGroupTask task) {
mAdapter.updateBtState(task.getKey(), true);
Log.d(TAG, String.format("group【%s】stop", task.getTaskName()));
}
@DownloadGroup.onTaskCancel void groupTaskCancel(DownloadGroupTask task) {
@ -129,6 +130,7 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
@DownloadGroup.onTaskFail void groupTaskFail(DownloadGroupTask task) {
mAdapter.updateBtState(task.getKey(), true);
Log.d(TAG, String.format("group【%s】fail", task.getTaskName()));
}
@DownloadGroup.onTaskComplete void taskComplete(DownloadGroupTask task) {

@ -1,8 +1,11 @@
package com.arialyy.simple.test;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivityTestBinding;
@ -16,9 +19,13 @@ public class AnyRunActivity extends BaseActivity<ActivityTestBinding> {
String[] urls;
int index = 0;
//String URL = "http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk";
//String URL = "http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk";
private final String URL = "ftp://192.168.29.140:21/download/AriaPrj.rar";
//String URL = "http://58.213.157.242:8081/sims_file/rest/v1/file/mshd_touchscreen_ms/guideFile/41c33556-dc4a-4d78-bb76-b9f627f94448.mp4/%E5%85%AB%E5%8D%A6%E6%B4%B2%E5%8D%97%E4%BA%AC%E5%86%9C%E4%B8%9A%E5%98%89%E5%B9%B4%E5%8D%8E0511.mp4";
//String URL = "http://d1.showself.com/download/showself_android-s236279_release.apk";
String URL = "http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk";
//private final String URL = "ftp://192.168.29.140:21/download/AriaPrj.rar";
//String URL = "https://dl.genymotion.com/releases/genymotion-2.12.1/genymotion-2.12.1-vbox.exe";
//String URL = "ftp://192.168.29.140:21/download/SDK_Demo-release.apk";
//String URL = "ftp://z:z@dygod18.com:21211/[电影天堂www.dy2018.com]猩球崛起3:终极之战BD国英双语中英双字.mkv";
@Override protected int setLayoutId() {
return R.layout.activity_test;
@ -30,6 +37,8 @@ public class AnyRunActivity extends BaseActivity<ActivityTestBinding> {
mBar.setVisibility(View.GONE);
module = new AnyRunnModule(this);
urls = getResources().getStringArray(R.array.group_urls);
DownloadTaskEntity entity = Aria.download(this).getDownloadTask(URL);
Log.d(TAG, entity + "");
}
public void onClick(View view) {
@ -42,7 +51,8 @@ public class AnyRunActivity extends BaseActivity<ActivityTestBinding> {
//}
//for (int i = 0; i < 10; i++) {
module.startFtp(URL);
//module.startFtp(URL);
module.start(URL);
//}
//List<AbsEntity> list = Aria.download(this).getTotalTaskList();
//ALog.d(TAG, "size ==> " + list.size());

@ -10,6 +10,7 @@ import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.frame.util.show.L;
import java.io.File;
import java.net.Proxy;
/**
* Created by laoyuyu on 2018/4/13.
@ -38,7 +39,7 @@ public class AnyRunnModule {
}
@Download.onTaskRunning protected void running(DownloadTask task) {
Log.d(TAG, "running");
Log.d(TAG, "running;Percent = " + task.getPercent());
}
@Download.onTaskResume void taskResume(DownloadTask task) {
@ -68,7 +69,8 @@ public class AnyRunnModule {
.load(url)
//.addHeader("Accept-Encoding", "gzip")
.setRequestMode(RequestEnum.GET)
.setFilePath(Environment.getExternalStorageDirectory().getPath() + "/ggsg123456.apk")
.setUrlProxy(Proxy.NO_PROXY)
.setFilePath(Environment.getExternalStorageDirectory().getPath() + "/abcds.exe")
//.resetState()
.start();
//String[] urls = new String[] {

@ -1,5 +1,6 @@
package com.arialyy.simple.test;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
@ -7,6 +8,7 @@ import com.arialyy.annotations.Upload;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.common.RequestEnum;
import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity;
@ -22,8 +24,8 @@ public class TestActivity extends BaseActivity<ActivityTestBinding> {
//String URL = "http://58.210.9.131/tpk/sipgt//TDLYZTGH.tpk"; //chunked 下载
//private final String URL = "ftp://192.168.1.3:21/download//AriaPrj.rar";
private final String FILE_PATH = "/mnt/sdcard/AriaPrj.rar";
//private final String URL = "ftp://192.168.29.140:21/aa//你好";
private final String URL = "ftp://192.168.29.140:21/upload/";
private final String URL = "ftp://192.168.1.2:21/aa//你好";
@Override protected int setLayoutId() {
return R.layout.activity_test;
@ -81,6 +83,8 @@ public class TestActivity extends BaseActivity<ActivityTestBinding> {
.setUploadUrl(URL)
.setExtendField("韩寒哈大双")
.start();
//Uri uri = Uri.parse("ftp://z:z@dygod18.com:21211/[电影天堂www.dy2018.com]猩球崛起3:终极之战BD国英双语中英双字.mkv");
//ALog.d(TAG, "sh = " + uri.getScheme() + ", user = " + uri.getUserInfo() + ", host = " + uri.getHost() + ", port = " + uri.getPort() + " remotePath = " + uri.getPath());
break;
case R.id.stop:
Aria.upload(this).loadFtp(FILE_PATH).stop();

@ -64,7 +64,7 @@
</string-array>
<string-array name="group_urls_1">
<!--<item>http://hzdown.muzhiwan.com/2017/05/08/nl.noio.kingdom_59104935e56f0.apk</item>-->
<item>http://hzdown.muzhiwan.com/2017/05/08/nl.noio.kingdom_59104935e56f0.apk</item>
<!--<item>https://atom-installer.github.com/v1.13.0/AtomSetup.exe</item>-->
<item>http://hzdown.muzhiwan.com/2017/09/05/com.mir.iphone.empire83jie.mzw_59ae6d5a3638d.apk</item>
</string-array>
@ -79,9 +79,14 @@
<item>http://static.gaoshouyou.com/d/92/12/5592a647b8126755647abbe8074fde39.apk</item>
</string-array>
<string-array name="group_url4">
<item>http://120.79.135.3/img/20180601/VR Karts Sprint.ver.1.04.build.15_crack_align.apk</item>
<item>http://120.79.135.3/img/20180601/main.11.com.daydvr.acefishing.vr.freefull.google.global.android.common.obb</item>
</string-array>
<string-array name="group_names">
<!--<item>王者荣耀.apk</item>-->
<!--<item>战斗吧剑灵.apk</item>-->
<item>战斗吧剑灵.apk</item>
<item>天魔幻想.apk</item>
</string-array>

@ -1,6 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.arialyy.aria">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:supportsRtl="true">

@ -366,6 +366,11 @@ class Configuration {
String caName;
/**
* 下载线程数下载线程数不能小于1
* 注意
* 1线程下载数改变后新的下载任务才会生效
* 2如果任务大小小于1m该设置不会生效
* 3从3.4.1开始如果线程数为1文件初始化时将不再预占用对应长度的空间下载多少byte则占多大的空间
* 对于采用多线程的任务或旧任务依然采用原来的文件空间占用方式
*/
int threadNum = 3;
@ -374,26 +379,6 @@ class Configuration {
*/
int maxSpeed = 0;
/**
* 是否开启动态文件开启动态文件后初始化时将不占用磁盘空间下载多少byte占多少空间效果见chrome的下载
* 注意
* 1使用该功能将自动关闭多线程下载
* 2对于已经采用了多线程的任务依然采用原来的下载方式
* 3原本参数是true任务没下载完成就参数改为false那么没下载完成的任务还是会按照参数修改前的方式下载只有新任务才会根据参数调用不同的下载方式
* {@code true}使用
*/
boolean openDynamicFile = true;
public DownloadConfig setOpenDynamicFile(boolean openDynamicFile) {
this.openDynamicFile = openDynamicFile;
saveKey("openDynamicFile", String.valueOf(openDynamicFile));
return this;
}
public boolean isOpenDynamicFile() {
return openDynamicFile;
}
public DownloadConfig setMaxTaskNum(int maxTaskNum) {
oldMaxTaskNum = this.maxTaskNum;
this.maxTaskNum = maxTaskNum;

@ -39,7 +39,7 @@ task clean(type: Delete) {
ext {
userOrg = 'arialyy'
groupId = 'com.arialyy.aria'
publishVersion = '3.4.1'
publishVersion = '3.4.2_dev6'
// publishVersion = '1.0.3' //FTP插件
repoName='maven'
desc = 'android 下载框架'

Loading…
Cancel
Save