merge dev code

pull/330/head
AriaLyy 8 years ago
commit 509aa32f6a
  1. 12
      Aria/bintray-release.gradle
  2. 52
      Aria/build.gradle
  3. 3
      Aria/src/main/java/com/arialyy/aria/core/command/AddCmd.java
  4. 30
      Aria/src/main/java/com/arialyy/aria/core/command/CmdFactory.java
  5. 51
      Aria/src/main/java/com/arialyy/aria/core/command/ResumeAllCmd.java
  6. 20
      Aria/src/main/java/com/arialyy/aria/core/command/StopAllCmd.java
  7. 18
      Aria/src/main/java/com/arialyy/aria/core/download/ConnectionHelp.java
  8. 23
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadReceiver.java
  9. 2
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTaskEntity.java
  10. 19
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadUtil.java
  11. 24
      Aria/src/main/java/com/arialyy/aria/core/queue/AbsTaskQueue.java
  12. 17
      Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java
  13. 2
      Aria/src/main/java/com/arialyy/aria/core/scheduler/AbsSchedulers.java
  14. 3
      Aria/src/main/java/com/arialyy/aria/util/CommonUtil.java
  15. 12
      AriaAnnotations/bintray-release.gradle
  16. 13
      AriaAnnotations/build.gradle
  17. 25
      AriaAnnotations/src/main/java/com/arialyy/annotations/AriaConstance.java
  18. 16
      AriaAnnotations/src/main/java/com/arialyy/annotations/Download.java
  19. 13
      AriaAnnotations/src/main/java/com/arialyy/annotations/Upload.java
  20. 12
      AriaCompiler/bintray-release.gradle
  21. 13
      AriaCompiler/build.gradle
  22. 200
      AriaCompiler/src/main/java/com/arialyy/compiler/ElementHandle.java
  23. 21
      AriaCompiler/src/main/java/com/arialyy/compiler/ProxyConstance.java
  24. 3
      AriaCompiler/src/main/java/com/arialyy/compiler/ProxyEntity.java
  25. 53
      README.md
  26. 1
      app/src/main/AndroidManifest.xml
  27. 4
      app/src/main/assets/aria_config.xml
  28. 5
      app/src/main/java/com/arialyy/simple/MainActivity.java
  29. 39
      app/src/main/java/com/arialyy/simple/download/SingleTaskActivity.java
  30. 6
      app/src/main/java/com/arialyy/simple/download/fragment_download/FragmentActivity.java
  31. 5
      app/src/main/java/com/arialyy/simple/download/multi_download/DownloadAdapter.java
  32. 26
      app/src/main/java/com/arialyy/simple/download/multi_download/MultiDownloadActivity.java
  33. 74
      app/src/main/java/com/arialyy/simple/test/TestMutilTaskSysDownload.java
  34. 1
      app/src/main/res/layout/activity_fragment.xml
  35. 9
      app/src/main/res/layout/activity_main.xml
  36. 22
      app/src/main/res/layout/test_activity_multi.xml
  37. 3
      app/src/main/res/menu/menu_highest_priority.xml
  38. 10
      app/src/main/res/menu/menu_mutil_task.xml
  39. 2
      build.gradle
  40. 1
      gradle/wrapper/gradle-wrapper.properties

@ -0,0 +1,12 @@
apply plugin: 'bintray-release'
publish {
artifactId = 'aria-core'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaApi'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}

@ -1,5 +1,4 @@
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
apply plugin: 'bintray-release'
android { android {
compileSdkVersion 23 compileSdkVersion 23
@ -23,53 +22,8 @@ dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs') compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1'
compile project(':AriaCompiler') // compile project(':AriaCompiler')
// compile project(':AriaAnnotations') compile project(':AriaAnnotations')
} }
apply from: 'bintray-release.gradle'
//apply from: 'jcenter.gradle' //apply from: 'jcenter.gradle'
// Jar
//task androidJar(type: Jar) {
// dependsOn assemble
// group 'Build'
// description 'blah blah'
// from zipTree(
// 'build/intermediates/bundles/release/classes.jar')
// from zipTree(
// '../AriaCompiler/build/libs/AriaCompiler.jar')
// from zipTree(
// '../AriaAnnotation/build/libs/AriaAnnotation.jar')
//
//}
//
//
//// javadoc tasks
//android.libraryVariants.all { variant ->
// task("javadoc${variant.name.capitalize()}", type: Javadoc) {
// description "Generates Javadoc for $variant.name."
// group 'Docs'
// source = variant.javaCompile.source
// source "../AriaAnnotation/src/main/java"
//
// exclude '**/BuildConfig.java'
// exclude '**/R.java'
// }
//}
publish {
artifactId = 'aria-core'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaApi'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}
//task copyJar(type: Copy) {
// from('build/libs/permission-lib.jar')
// into('../output/')
// rename ('permission-lib.jar', 'mpermissions.jar')
//}

@ -17,6 +17,7 @@
package com.arialyy.aria.core.command; package com.arialyy.aria.core.command;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.AbsTaskEntity; import com.arialyy.aria.core.inf.AbsTaskEntity;
@ -34,10 +35,10 @@ class AddCmd<T extends AbsTaskEntity> extends AbsCmd<T> {
if (!canExeCmd) return; if (!canExeCmd) return;
ITask task = mQueue.getTask(mEntity.getEntity()); ITask task = mQueue.getTask(mEntity.getEntity());
if (task == null) { if (task == null) {
mEntity.getEntity().setState(IEntity.STATE_WAIT);
mQueue.createTask(mTargetName, mEntity); mQueue.createTask(mTargetName, mEntity);
} else { } else {
Log.w(TAG, "添加命令执行失败,【该任务已经存在】"); Log.w(TAG, "添加命令执行失败,【该任务已经存在】");
} }
} }
} }

@ -48,8 +48,14 @@ public class CmdFactory {
* 设置任务为最高优先级 * 设置任务为最高优先级
*/ */
public static final int TASK_HIGHEST_PRIORITY = 0x128; public static final int TASK_HIGHEST_PRIORITY = 0x128;
/**
public static final int TASK_SINGLE = 0x126; * 停止所有任务
*/
public static final int TASK_STOP_ALL = 0x129;
/**
* 恢复所有停止的任务
*/
public static final int TASK_RESUME_ALL = 0x130;
private static volatile CmdFactory INSTANCE = null; private static volatile CmdFactory INSTANCE = null;
@ -70,23 +76,25 @@ public class CmdFactory {
* @param target 创建任务的对象 * @param target 创建任务的对象
* @param entity 下载实体 * @param entity 下载实体
* @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link * @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link
* #TASK_STOP}{@link #TASK_HIGHEST_PRIORITY} * #TASK_STOP}{@link #TASK_HIGHEST_PRIORITY}{@link #TASK_STOP_ALL}{@link #TASK_RESUME_ALL}
*/ */
public <T extends AbsTaskEntity> AbsCmd createCmd(String target, T entity, int type) { public <T extends AbsTaskEntity> AbsCmd<T> createCmd(String target, T entity, int type) {
switch (type) { switch (type) {
case TASK_CREATE: case TASK_CREATE:
return new AddCmd(target, entity); return new AddCmd<>(target, entity);
case TASK_RESUME: case TASK_RESUME:
case TASK_START: case TASK_START:
return new StartCmd(target, entity); return new StartCmd<>(target, entity);
case TASK_CANCEL: case TASK_CANCEL:
return new CancelCmd(target, entity); return new CancelCmd<>(target, entity);
case TASK_STOP: case TASK_STOP:
return new StopCmd(target, entity); return new StopCmd<>(target, entity);
case TASK_HIGHEST_PRIORITY: case TASK_HIGHEST_PRIORITY:
return new HighestPriorityCmd(target, entity); return new HighestPriorityCmd<>(target, entity);
case TASK_SINGLE: case TASK_STOP_ALL:
//return new SingleCmd(target, entity); return new StopAllCmd<>(target, entity);
case TASK_RESUME_ALL:
return new ResumeAllCmd<>(target, entity);
default: default:
return null; return null;
} }

@ -0,0 +1,51 @@
package com.arialyy.aria.core.command;
import android.util.Log;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.orm.DbEntity;
import java.util.List;
/**
* Created by AriaL on 2017/6/13.
* 恢复所有停止的任务
* 1.如果执行队列没有满则开始下载任务直到执行队列满
* 2.如果队列执行队列已经满了则将所有任务添加到等待队列中
*/
final class ResumeAllCmd<T extends AbsTaskEntity> extends AbsCmd<T> {
/**
* @param targetName 产生任务的对象名
*/
ResumeAllCmd(String targetName, T entity) {
super(targetName, entity);
}
@Override public void executeCmd() {
List<DownloadEntity> allEntity =
DbEntity.findDatas(DownloadEntity.class, "state=?", IEntity.STATE_STOP + "");
for (DownloadEntity entity : allEntity) {
int exeNum = mQueue.getExeTaskNum();
if (exeNum == 0 || exeNum < mQueue.getMaxTaskNum()) {
ITask task = createTask(entity);
mQueue.startTask(task);
} else {
entity.setState(IEntity.STATE_WAIT);
createTask(entity);
}
}
}
private ITask createTask(DownloadEntity entity) {
ITask task = mQueue.getTask(entity);
if (task == null) {
DownloadTaskEntity taskEntity = new DownloadTaskEntity(entity);
task = mQueue.createTask(mTargetName, taskEntity);
} else {
Log.w(TAG, "添加命令执行失败,【该任务已经存在】");
}
return task;
}
}

@ -0,0 +1,20 @@
package com.arialyy.aria.core.command;
import com.arialyy.aria.core.inf.AbsTaskEntity;
/**
* Created by AriaL on 2017/6/13.
* 停止所有任务的命令并清空所有等待队列
*/
final class StopAllCmd<T extends AbsTaskEntity> extends AbsCmd<T> {
/**
* @param targetName 产生任务的对象名
*/
StopAllCmd(String targetName, T entity) {
super(targetName, entity);
}
@Override public void executeCmd() {
mQueue.stopAllTask();
}
}

@ -63,22 +63,27 @@ class ConnectionHelp {
static HttpURLConnection setConnectParam(DownloadTaskEntity entity, HttpURLConnection conn) static HttpURLConnection setConnectParam(DownloadTaskEntity entity, HttpURLConnection conn)
throws ProtocolException { throws ProtocolException {
conn.setRequestMethod(entity.requestEnum.name); conn.setRequestMethod(entity.requestEnum.name);
Set<String> keys = null;
if (entity.headers != null && entity.headers.size() > 0) { if (entity.headers != null && entity.headers.size() > 0) {
Set<String> keys = entity.headers.keySet(); keys = entity.headers.keySet();
for (String key : keys) { for (String key : keys) {
conn.setRequestProperty(key, entity.headers.get(key)); conn.setRequestProperty(key, entity.headers.get(key));
} }
} }
if (keys == null || !keys.contains("Charset")) {
conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Charset", "UTF-8");
}
if (keys == null || !keys.contains("User-Agent")) {
conn.setRequestProperty("User-Agent", conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
}
if (keys == null || !keys.contains("Accept")) {
StringBuilder accept = new StringBuilder(); StringBuilder accept = new StringBuilder();
accept.append("image/gif, ") accept.append("image/gif, ")
.append("image/jpeg, ") .append("image/jpeg, ")
.append("image/pjpeg, ") .append("image/pjpeg, ")
.append("image/webp, ") .append("image/webp, ")
.append("image/*, ") .append("application/xml, ")
.append("application/xml")
.append("application/xaml+xml, ") .append("application/xaml+xml, ")
.append("application/xhtml+xml, ") .append("application/xhtml+xml, ")
.append("application/x-shockwave-flash, ") .append("application/x-shockwave-flash, ")
@ -92,9 +97,16 @@ class ConnectionHelp {
.append("text/html, ") .append("text/html, ")
.append("*/*"); .append("*/*");
conn.setRequestProperty("Accept", accept.toString()); conn.setRequestProperty("Accept", accept.toString());
}
if (keys == null || !keys.contains("Accept-Encoding")) {
conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("Accept-Encoding", "identity");
}
if (keys == null || !keys.contains("Accept-Charset")) {
conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Accept-Charset", "UTF-8");
}
if (keys == null || !keys.contains("Connection")) {
conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Connection", "Keep-Alive");
}
//302获取重定向地址 //302获取重定向地址
conn.setInstanceFollowRedirects(false); conn.setInstanceFollowRedirects(false);
return conn; return conn;

@ -17,6 +17,7 @@ package com.arialyy.aria.core.download;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.arialyy.aria.core.AriaManager; import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.ICmd;
import com.arialyy.aria.core.inf.IReceiver; import com.arialyy.aria.core.inf.IReceiver;
import com.arialyy.aria.core.command.CmdFactory; import com.arialyy.aria.core.command.CmdFactory;
import com.arialyy.aria.core.command.AbsCmd; import com.arialyy.aria.core.command.AbsCmd;
@ -133,19 +134,23 @@ public class DownloadReceiver implements IReceiver<DownloadEntity> {
} }
/** /**
* 停止所有正在下载的任务 * 停止所有正在下载的任务并清空等待队列
*/ */
@Override public void stopAllTask() { @Override public void stopAllTask() {
final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP); final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP);
List<DownloadEntity> allEntity = DbEntity.findAllData(DownloadEntity.class); ariaManager.setCmd(CmdFactory.getInstance()
List<AbsCmd> stopCmds = new ArrayList<>(); .createCmd(targetName, new DownloadTaskEntity(), CmdFactory.TASK_STOP_ALL)).exe();
for (DownloadEntity entity : allEntity) {
if (entity.getState() == DownloadEntity.STATE_RUNNING) {
stopCmds.add(
CommonUtil.createCmd(targetName, new DownloadTaskEntity(entity), CmdFactory.TASK_STOP));
} }
}
ariaManager.setCmds(stopCmds).exe(); /**
* 恢复所有正在下载的任务
* 1.如果执行队列没有满则开始下载任务直到执行队列满
* 2.如果队列执行队列已经满了则将所有任务添加到等待队列中
*/
public void resumeAllTask() {
final AriaManager ariaManager = AriaManager.getInstance(AriaManager.APP);
ariaManager.setCmd(CmdFactory.getInstance()
.createCmd(targetName, new DownloadTaskEntity(), CmdFactory.TASK_RESUME_ALL)).exe();
} }
/** /**

@ -25,6 +25,8 @@ public class DownloadTaskEntity extends AbsTaskEntity {
public DownloadEntity downloadEntity; public DownloadEntity downloadEntity;
public DownloadTaskEntity(){}
public DownloadTaskEntity(DownloadEntity downloadEntity) { public DownloadTaskEntity(DownloadEntity downloadEntity) {
this.downloadEntity = downloadEntity; this.downloadEntity = downloadEntity;
} }

@ -81,7 +81,7 @@ class DownloadUtil implements IDownloadUtil, Runnable {
+ ".properties"); + ".properties");
try { try {
if (!mConfigFile.exists()) { //记录文件被删除,则重新下载 if (!mConfigFile.exists()) { //记录文件被删除,则重新下载
handleNewTask(); isNewTask = true;
CommonUtil.createFile(mConfigFile.getPath()); CommonUtil.createFile(mConfigFile.getPath());
} else { } else {
isNewTask = !mDownloadFile.exists(); isNewTask = !mDownloadFile.exists();
@ -295,10 +295,6 @@ class DownloadUtil implements IDownloadUtil, Runnable {
return; return;
} }
int fileLength = conn.getContentLength(); int fileLength = conn.getContentLength();
if (fileLength < SUB_LEN) {
THREAD_NUM = 1;
CONSTANCE.THREAD_NUM = THREAD_NUM;
}
Properties pro = createConfigFile(fileLength); Properties pro = createConfigFile(fileLength);
int blockSize = fileLength / THREAD_NUM; int blockSize = fileLength / THREAD_NUM;
int[] recordL = new int[THREAD_NUM]; int[] recordL = new int[THREAD_NUM];
@ -325,7 +321,7 @@ class DownloadUtil implements IDownloadUtil, Runnable {
recordL[rl] = i; recordL[rl] = i;
rl++; rl++;
} else { } else {
handleNewTask(); handleNewTask(fileLength);
} }
if (isNewTask) { if (isNewTask) {
recordL[rl] = i; recordL[rl] = i;
@ -380,7 +376,7 @@ class DownloadUtil implements IDownloadUtil, Runnable {
//分配每条线程的下载区间 //分配每条线程的下载区间
pro = CommonUtil.loadConfig(mConfigFile); pro = CommonUtil.loadConfig(mConfigFile);
if (pro.isEmpty()) { if (pro.isEmpty()) {
handleNewTask(); handleNewTask(fileLength);
} else { } else {
Set<Object> keys = pro.keySet(); Set<Object> keys = pro.keySet();
int num = 0; int num = 0;
@ -390,7 +386,7 @@ class DownloadUtil implements IDownloadUtil, Runnable {
} }
} }
if (num == 0) { if (num == 0) {
handleNewTask(); handleNewTask(fileLength);
return pro; return pro;
} }
THREAD_NUM = num; THREAD_NUM = num;
@ -400,7 +396,7 @@ class DownloadUtil implements IDownloadUtil, Runnable {
if (state != null && Integer.parseInt(state + "") == 1) { if (state != null && Integer.parseInt(state + "") == 1) {
continue; continue;
} }
handleNewTask(); handleNewTask(fileLength);
return pro; return pro;
} }
} }
@ -412,9 +408,10 @@ class DownloadUtil implements IDownloadUtil, Runnable {
/** /**
* 处理新任务 * 处理新任务
*/ */
private void handleNewTask() { private void handleNewTask(long fileLength) {
isNewTask = true; isNewTask = true;
THREAD_NUM = AriaManager.getInstance(mContext).getDownloadConfig().getThreadNum(); THREAD_NUM = fileLength < SUB_LEN ? 1
: AriaManager.getInstance(mContext).getDownloadConfig().getThreadNum();
} }
/** /**

@ -17,11 +17,14 @@
package com.arialyy.aria.core.queue; package com.arialyy.aria.core.queue;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.AbsEntity; import com.arialyy.aria.core.inf.AbsEntity;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.inf.AbsTaskEntity; import com.arialyy.aria.core.inf.AbsTaskEntity;
import com.arialyy.aria.core.queue.pool.CachePool; import com.arialyy.aria.core.queue.pool.CachePool;
import com.arialyy.aria.core.queue.pool.ExecutePool; import com.arialyy.aria.core.queue.pool.ExecutePool;
import java.util.Set;
/** /**
* Created by lyy on 2017/2/23. * Created by lyy on 2017/2/23.
@ -33,6 +36,25 @@ abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntit
CachePool<TASK> mCachePool = new CachePool<>(); CachePool<TASK> mCachePool = new CachePool<>();
ExecutePool<TASK> mExecutePool; ExecutePool<TASK> mExecutePool;
/**
* 停止所有任务
*/
@Override public void stopAllTask() {
Set<String> exeKeys = mExecutePool.getAllTask().keySet();
for (String key : exeKeys) {
TASK task = mExecutePool.getAllTask().get(key);
if (task != null && task.isRunning()) task.stop();
}
Set<String> cacheKeys = mCachePool.getAllTask().keySet();
for (String key : cacheKeys) {
mExecutePool.removeTask(key);
}
}
@Override public int getMaxTaskNum() {
return AriaManager.getInstance(AriaManager.APP).getDownloadConfig().getMaxTaskNum();
}
/** /**
* 获取任务执行池 * 获取任务执行池
*/ */
@ -61,7 +83,7 @@ abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntit
* *
* @return 当前正在执行的任务数 * @return 当前正在执行的任务数
*/ */
@Override public int executePoolSize() { @Override public int getExeTaskNum() {
return mExecutePool.size(); return mExecutePool.size();
} }

@ -32,8 +32,14 @@ import com.arialyy.aria.core.upload.UploadTaskEntity;
*/ */
public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntity, ENTITY extends IEntity> { public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntity, ENTITY extends IEntity> {
/**
* 停止所有任务
*/
void stopAllTask();
/** /**
* 设置任务为最高优先级任务 * 设置任务为最高优先级任务
*
* @param task {@link DownloadTask}{@link UploadTask} * @param task {@link DownloadTask}{@link UploadTask}
*/ */
void setTaskHighestPriority(TASK task); void setTaskHighestPriority(TASK task);
@ -67,9 +73,9 @@ public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntit
void reTryStart(TASK task); void reTryStart(TASK task);
/** /**
* 任务池队列大小 * 获取正在执行的任务数量
*/ */
int executePoolSize(); int getExeTaskNum();
/** /**
* 任务缓存池大小 * 任务缓存池大小
@ -79,10 +85,15 @@ public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends AbsTaskEntit
/** /**
* 设置最大任务数 * 设置最大任务数
* *
* @param newMaxNum 下载任务数 * @param newMaxNum 最大任务数
*/ */
void setMaxTaskNum(int newMaxNum); void setMaxTaskNum(int newMaxNum);
/**
* 获取可执行队列的大小
*/
int getMaxTaskNum();
/** /**
* 创建一个新的任务创建时只是将新任务存储到缓存池 * 创建一个新的任务创建时只是将新任务存储到缓存池
* *

@ -140,7 +140,7 @@ public abstract class AbsSchedulers<TASK_ENTITY extends AbsTaskEntity, ENTITY ex
} }
case CANCEL: case CANCEL:
mQueue.removeTask(entity); mQueue.removeTask(entity);
if (mQueue.executePoolSize() < AriaManager.getInstance(AriaManager.APP) if (mQueue.getExeTaskNum() < AriaManager.getInstance(AriaManager.APP)
.getUploadConfig() .getUploadConfig()
.getMaxTaskNum()) { .getMaxTaskNum()) {
startNextTask(); startNextTask();

@ -352,6 +352,9 @@ public class CommonUtil {
* @param size file.length() 获取文件大小 * @param size file.length() 获取文件大小
*/ */
public static String formatFileSize(double size) { public static String formatFileSize(double size) {
if (size < 0) {
return "0kb";
}
double kiloByte = size / 1024; double kiloByte = size / 1024;
if (kiloByte < 1) { if (kiloByte < 1) {
return size + "b"; return size + "b";

@ -0,0 +1,12 @@
apply plugin: 'bintray-release'
publish {
artifactId = 'aria-annotations'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaAnnotations'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}

@ -1,5 +1,4 @@
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'bintray-release'
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding = "UTF-8" options.encoding = "UTF-8"
@ -12,14 +11,4 @@ dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) compile fileTree(dir: 'libs', include: ['*.jar'])
} }
publish { apply from: 'bintray-release.gradle'
artifactId = 'aria-annotations'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaAnnotations'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}

@ -0,0 +1,25 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.annotations;
/**
* Created by AriaL on 2017/6/14.
*/
public interface AriaConstance {
String NO_URL = "";
}

@ -25,66 +25,77 @@ import java.lang.annotation.Target;
* Aria下载事件被注解的方法中参数仅能有一个参数类型为{@link com.arialyy.aria.core.download.DownloadTask} * Aria下载事件被注解的方法中参数仅能有一个参数类型为{@link com.arialyy.aria.core.download.DownloadTask}
* <pre> * <pre>
* <code> * <code>
* {@literal @}Download.onPre(DownloadUrl)
* protected void onPre(DownloadTask task) { * protected void onPre(DownloadTask task) {
* if (task.getKey().equals(DOWNLOAD_URL)) {
* mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize()).sendToTarget(); * mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize()).sendToTarget();
* } * }
* }
* </code> * </code>
* </pre> * </pre>
* {@literal @}Download.onPre("http://www.baidu.com")如果你的注解中增加了url描述
* 则表示所有下载任务中只有下载地址为"http://www.baidu.com"的任务才能回调该注解的方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Download { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Download {
/** /**
* 如果你在方法中添加{@code @Download.onPre}注解在预处理完成时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onPre}注解在预处理完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onPre { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onPre {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskPre}注解在任务预处理完成时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskPre}注解在任务预处理完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskPre { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskPre {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskResume}注解在任务恢复下载时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskResume}注解在任务恢复下载时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskResume { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskResume {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskStart}注解在任务开始下载时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskStart}注解在任务开始下载时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStart { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStart {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskStop}注解在任务停止时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskStop}注解在任务停止时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStop { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStop {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskCancel}l注解在任务取消时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskCancel}l注解在任务取消时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskCancel { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskCancel {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskFail)注解在任务预失败时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskFail)注解在任务预失败时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskFail { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskFail {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskComplete}注解在任务完成时Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskComplete}注解在任务完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskComplete { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskComplete {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Download.onTaskRunning}注解在任务正在下载Aria会调用该方法 * 如果你在方法中添加{@code @Download.onTaskRunning}注解在任务正在下载Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskRunning { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskRunning {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
@ -92,5 +103,6 @@ import java.lang.annotation.Target;
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD)
public @interface onNoSupportBreakPoint { public @interface onNoSupportBreakPoint {
String[] value() default { AriaConstance.NO_URL };
} }
} }

@ -25,11 +25,14 @@ import java.lang.annotation.Target;
* Aria下载事件被注解的方法中参数仅能有一个参数类型为{@link com.arialyy.aria.core.upload.UploadTask} * Aria下载事件被注解的方法中参数仅能有一个参数类型为{@link com.arialyy.aria.core.upload.UploadTask}
* <pre> * <pre>
* <code> * <code>
* {@literal @}Upload.onPre
* protected void onPre(UploadTask task) { * protected void onPre(UploadTask task) {
* L.d(TAG, "fileSize = " + task.getConvertFileSize()); * L.d(TAG, "fileSize = " + task.getConvertFileSize());
* } * }
* </code> * </code>
* </pre> * </pre>
* {@literal @}Upload.onPre("/mnt/sdcard/test.zip")如果你的注解中增加了path描述
* 则表示所有上传任务中只有上传路径为"/mnt/sdcard/test.zip"的任务才能回调该注解的方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Upload { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Upload {
@ -37,12 +40,14 @@ import java.lang.annotation.Target;
* 如果你在方法中添加{@code @Upload.onPre}注解在预处理完成时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onPre}注解在预处理完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onPre { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onPre {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskPre}注解在任务预处理完成时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskPre}注解在任务预处理完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskPre { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskPre {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
@ -50,40 +55,47 @@ import java.lang.annotation.Target;
*/ */
//@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskResume { //@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskResume {
//} //}
/** /**
* 如果你在方法中添加{@code @Upload.onTaskStart}注解在任务开始下载时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskStart}注解在任务开始下载时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStart { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStart {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskStop}注解在任务停止时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskStop}注解在任务停止时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStop { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskStop {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskCancel}l注解在任务取消时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskCancel}l注解在任务取消时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskCancel { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskCancel {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskFail)注解在任务预失败时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskFail)注解在任务预失败时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskFail { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskFail {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskComplete}注解在任务完成时Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskComplete}注解在任务完成时Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskComplete { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskComplete {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
* 如果你在方法中添加{@code @Upload.onTaskRunning}注解在任务正在下载Aria会调用该方法 * 如果你在方法中添加{@code @Upload.onTaskRunning}注解在任务正在下载Aria会调用该方法
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskRunning { @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface onTaskRunning {
String[] value() default { AriaConstance.NO_URL };
} }
/** /**
@ -91,5 +103,6 @@ import java.lang.annotation.Target;
*/ */
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD)
public @interface onNoSupportBreakPoint { public @interface onNoSupportBreakPoint {
String[] value() default { AriaConstance.NO_URL };
} }
} }

@ -0,0 +1,12 @@
apply plugin: 'bintray-release'
publish {
artifactId = 'aria-compiler'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaCompiler'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}

@ -1,5 +1,4 @@
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'bintray-release'
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding = "UTF-8" options.encoding = "UTF-8"
@ -15,14 +14,4 @@ dependencies {
compile project(':AriaAnnotations') compile project(':AriaAnnotations')
} }
publish { apply from: 'bintray-release.gradle'
artifactId = 'aria-compiler'
userOrg = rootProject.userOrg
groupId = rootProject.groupId
// uploadName = rootProject.uploadName
uploadName = 'AriaCompiler'
publishVersion = rootProject.publishVersion
description = rootProject.description
website = rootProject.website
licences = rootProject.licences
}

@ -18,6 +18,7 @@ package com.arialyy.compiler;
import com.arialyy.annotations.Download; import com.arialyy.annotations.Download;
import com.arialyy.annotations.Upload; import com.arialyy.annotations.Upload;
import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.MethodSpec;
@ -26,7 +27,9 @@ import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.ParameterizedTypeName;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -63,40 +66,32 @@ class ElementHandle {
* PackageElement 一般代表Package * PackageElement 一般代表Package
*/ */
void handleDownload(RoundEnvironment roundEnv) { void handleDownload(RoundEnvironment roundEnv) {
saveMethod(true, roundEnv, Download.onNoSupportBreakPoint.class); saveMethod(true, roundEnv, Download.onNoSupportBreakPoint.class,
saveMethod(true, roundEnv, Download.onPre.class); ProxyConstance.DOWNLOAD_TASK_NO_SUPPORT_BREAKPOINT);
saveMethod(true, roundEnv, Download.onTaskCancel.class); saveMethod(true, roundEnv, Download.onPre.class, ProxyConstance.DOWNLOAD_PRE);
saveMethod(true, roundEnv, Download.onTaskComplete.class); saveMethod(true, roundEnv, Download.onTaskCancel.class, ProxyConstance.DOWNLOAD_TASK_CANCEL);
saveMethod(true, roundEnv, Download.onTaskFail.class); saveMethod(true, roundEnv, Download.onTaskComplete.class,
saveMethod(true, roundEnv, Download.onTaskPre.class); ProxyConstance.DOWNLOAD_TASK_COMPLETE);
saveMethod(true, roundEnv, Download.onTaskResume.class); saveMethod(true, roundEnv, Download.onTaskFail.class, ProxyConstance.DOWNLOAD_TASK_FAIL);
saveMethod(true, roundEnv, Download.onTaskRunning.class); saveMethod(true, roundEnv, Download.onTaskPre.class, ProxyConstance.DOWNLOAD_TASK_PRE);
saveMethod(true, roundEnv, Download.onTaskStart.class); saveMethod(true, roundEnv, Download.onTaskResume.class, ProxyConstance.DOWNLOAD_TASK_RESUME);
saveMethod(true, roundEnv, Download.onTaskStop.class); saveMethod(true, roundEnv, Download.onTaskRunning.class, ProxyConstance.DOWNLOAD_TASK_RUNNING);
saveMethod(true, roundEnv, Download.onTaskStart.class, ProxyConstance.DOWNLOAD_TASK_START);
saveMethod(true, roundEnv, Download.onTaskStop.class, ProxyConstance.DOWNLOAD_TASK_STOP);
} }
void handleUpload(RoundEnvironment roundEnv) { void handleUpload(RoundEnvironment roundEnv) {
saveMethod(false, roundEnv, Upload.onNoSupportBreakPoint.class); saveMethod(false, roundEnv, Upload.onNoSupportBreakPoint.class,
saveMethod(false, roundEnv, Upload.onPre.class); ProxyConstance.UPLOAD_TASK_NO_SUPPORT_BREAKPOINT);
saveMethod(false, roundEnv, Upload.onTaskCancel.class); saveMethod(false, roundEnv, Upload.onPre.class, ProxyConstance.UPLOAD_PRE);
saveMethod(false, roundEnv, Upload.onTaskComplete.class); saveMethod(false, roundEnv, Upload.onTaskCancel.class, ProxyConstance.UPLOAD_TASK_CANCEL);
saveMethod(false, roundEnv, Upload.onTaskFail.class); saveMethod(false, roundEnv, Upload.onTaskComplete.class, ProxyConstance.UPLOAD_TASK_COMPLETE);
saveMethod(false, roundEnv, Upload.onTaskPre.class); saveMethod(false, roundEnv, Upload.onTaskFail.class, ProxyConstance.UPLOAD_TASK_FAIL);
saveMethod(false, roundEnv, Upload.onTaskPre.class, ProxyConstance.UPLOAD_TASK_PRE);
//saveMethod(false, roundEnv, Upload.onTaskResume.class); //saveMethod(false, roundEnv, Upload.onTaskResume.class);
saveMethod(false, roundEnv, Upload.onTaskRunning.class); saveMethod(false, roundEnv, Upload.onTaskRunning.class, ProxyConstance.UPLOAD_TASK_RUNNING);
saveMethod(false, roundEnv, Upload.onTaskStart.class); saveMethod(false, roundEnv, Upload.onTaskStart.class, ProxyConstance.UPLOAD_TASK_START);
saveMethod(false, roundEnv, Upload.onTaskStop.class); saveMethod(false, roundEnv, Upload.onTaskStop.class, ProxyConstance.UPLOAD_TASK_STOP);
}
void printMethods() {
//Set<String> keys = mMethods.keySet();
//for (String key : keys) {
// ProxyEntity entity = mMethods.get(key);
// for (String method : entity.methods) {
// PrintLog.getInstance().info(method);
// }
//}
PrintLog.getInstance().info("size ==> " + mMethods.size());
} }
/** /**
@ -157,16 +152,29 @@ class ElementHandle {
isDownload ? "DownloadTask" : "UploadTask"); isDownload ? "DownloadTask" : "UploadTask");
ParameterSpec parameterSpec = ParameterSpec parameterSpec =
ParameterSpec.builder(task, "task").addModifiers(Modifier.FINAL).build(); ParameterSpec.builder(task, "task").addModifiers(Modifier.FINAL).build();
StringBuilder sb = new StringBuilder();
sb.append("Set<String> keys = keyMapping.get(\"")
.append(methodName)
.append("\");\n");
sb.append("if (keys != null) {\n\tif (keys.contains(task.getKey())) {\n")
.append("\t\tobj.")
.append(methodName)
.append("(")
.append(isDownload ? "(DownloadTask)" : "(UploadTask)")
.append("task);\n")
.append("\t}\n} else {\n")
.append("\tobj.")
.append(methodName)
.append("(")
.append(isDownload ? "(DownloadTask)" : "(UploadTask)")
.append("task);\n}\n");
return MethodSpec.methodBuilder(annotation.getSimpleName()) return MethodSpec.methodBuilder(annotation.getSimpleName())
.addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.PUBLIC)
.returns(void.class) .returns(void.class)
.addParameter(parameterSpec) .addParameter(parameterSpec)
.addAnnotation(Override.class) .addAnnotation(Override.class)
.addCode("obj." .addCode(sb.toString())
+ methodName
+ "("
+ (isDownload ? "(DownloadTask)" : "(UploadTask)")
+ "task);\n")
.build(); .build();
} }
@ -184,6 +192,13 @@ class ElementHandle {
FieldSpec observerField = FieldSpec.builder(obj, "obj").addModifiers(Modifier.PRIVATE).build(); FieldSpec observerField = FieldSpec.builder(obj, "obj").addModifiers(Modifier.PRIVATE).build();
builder.addField(observerField); builder.addField(observerField);
//添加url映射表
FieldSpec mappingField = FieldSpec.builder(
ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class),
ParameterizedTypeName.get(ClassName.get(Set.class), ClassName.get(String.class))),
"keyMapping").addModifiers(Modifier.PRIVATE).initializer("new $T()", HashMap.class).build();
builder.addField(mappingField);
//添加注解方法 //添加注解方法
for (Class<? extends Annotation> annotation : entity.methods.keySet()) { for (Class<? extends Annotation> annotation : entity.methods.keySet()) {
MethodSpec method = MethodSpec method =
@ -191,6 +206,26 @@ class ElementHandle {
builder.addMethod(method); builder.addMethod(method);
} }
//增加构造函数
CodeBlock.Builder cb = CodeBlock.builder();
cb.add("Set<String> set = null;\n");
for (String methodName : entity.keyMappings.keySet()) {
Set<String> keys = entity.keyMappings.get(methodName);
if (keys == null || keys.size() == 0) continue;
StringBuilder sb = new StringBuilder();
sb.append("set = new $T();\n");
for (String key : keys) {
if (key.isEmpty()) continue;
sb.append("set.add(\"").append(key).append("\");\n");
}
sb.append("keyMapping.put(\"").append(methodName).append("\", ").append("set);\n");
cb.add(sb.toString(), ClassName.get(HashSet.class));
}
MethodSpec structure =
MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addCode(cb.build()).build();
builder.addMethod(structure);
//添加设置代理的类 //添加设置代理的类
ParameterSpec parameterSpec = ParameterSpec parameterSpec =
ParameterSpec.builder(Object.class, "obj").addModifiers(Modifier.FINAL).build(); ParameterSpec.builder(Object.class, "obj").addModifiers(Modifier.FINAL).build();
@ -222,7 +257,7 @@ class ElementHandle {
* 查找并保存扫描到的方法 * 查找并保存扫描到的方法
*/ */
private void saveMethod(boolean isDownload, RoundEnvironment roundEnv, private void saveMethod(boolean isDownload, RoundEnvironment roundEnv,
Class<? extends Annotation> annotationClazz) { Class<? extends Annotation> annotationClazz, int annotationType) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotationClazz)) { for (Element element : roundEnv.getElementsAnnotatedWith(annotationClazz)) {
ElementKind kind = element.getKind(); ElementKind kind = element.getKind();
if (kind == ElementKind.METHOD) { if (kind == ElementKind.METHOD) {
@ -236,14 +271,90 @@ class ElementHandle {
if (proxyEntity == null) { if (proxyEntity == null) {
proxyEntity = new ProxyEntity(); proxyEntity = new ProxyEntity();
proxyEntity.isDownlaod = isDownload; proxyEntity.isDownlaod = isDownload;
//proxyEntity.packageName = classElement.getQualifiedName().toString();
proxyEntity.packageName = packageElement.getQualifiedName().toString(); proxyEntity.packageName = packageElement.getQualifiedName().toString();
proxyEntity.className = classElement.getSimpleName().toString(); proxyEntity.className = classElement.getSimpleName().toString();
mMethods.put(className, proxyEntity); mMethods.put(className, proxyEntity);
} }
proxyEntity.methods.put(annotationClazz, methodName); proxyEntity.methods.put(annotationClazz, methodName);
proxyEntity.keyMappings.put(methodName, getValues(method, isDownload, annotationType));
}
}
} }
/**
* 获取注解的内容
*/
private Set<String> getValues(ExecutableElement method, boolean isDownload, int annotationType) {
String[] keys = null;
if (isDownload) {
switch (annotationType) {
case ProxyConstance.DOWNLOAD_PRE:
keys = method.getAnnotation(Download.onPre.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_PRE:
keys = method.getAnnotation(Download.onTaskPre.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_RESUME:
keys = method.getAnnotation(Download.onTaskResume.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_START:
keys = method.getAnnotation(Download.onTaskStart.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_RUNNING:
keys = method.getAnnotation(Download.onTaskRunning.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_STOP:
keys = method.getAnnotation(Download.onTaskStop.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_COMPLETE:
keys = method.getAnnotation(Download.onTaskComplete.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_CANCEL:
keys = method.getAnnotation(Download.onTaskCancel.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_FAIL:
keys = method.getAnnotation(Download.onTaskFail.class).value();
break;
case ProxyConstance.DOWNLOAD_TASK_NO_SUPPORT_BREAKPOINT:
keys = method.getAnnotation(Download.onNoSupportBreakPoint.class).value();
break;
} }
} else {
switch (annotationType) {
case ProxyConstance.UPLOAD_PRE:
keys = method.getAnnotation(Upload.onPre.class).value();
break;
case ProxyConstance.UPLOAD_TASK_PRE:
keys = method.getAnnotation(Upload.onTaskPre.class).value();
break;
case ProxyConstance.UPLOAD_TASK_RESUME:
//keys = method.getAnnotation(Upload.onTaskResume.class).value();
break;
case ProxyConstance.UPLOAD_TASK_START:
keys = method.getAnnotation(Upload.onTaskStart.class).value();
break;
case ProxyConstance.UPLOAD_TASK_RUNNING:
keys = method.getAnnotation(Upload.onTaskRunning.class).value();
break;
case ProxyConstance.UPLOAD_TASK_STOP:
keys = method.getAnnotation(Upload.onTaskStop.class).value();
break;
case ProxyConstance.UPLOAD_TASK_COMPLETE:
keys = method.getAnnotation(Upload.onTaskComplete.class).value();
break;
case ProxyConstance.UPLOAD_TASK_CANCEL:
keys = method.getAnnotation(Upload.onTaskCancel.class).value();
break;
case ProxyConstance.UPLOAD_TASK_FAIL:
keys = method.getAnnotation(Upload.onTaskFail.class).value();
break;
case ProxyConstance.UPLOAD_TASK_NO_SUPPORT_BREAKPOINT:
keys = method.getAnnotation(Upload.onNoSupportBreakPoint.class).value();
break;
}
}
return keys == null ? null : convertSet(keys);
} }
/** /**
@ -272,6 +383,21 @@ class ElementHandle {
} }
} }
/**
* 字符串数组转set
*
* @param keys 注解中查到的key
*/
private Set<String> convertSet(final String[] keys) {
if (keys == null || keys.length == 0) {
return null;
}
if (keys[0].isEmpty()) return null;
Set<String> set = new HashSet<>();
Collections.addAll(set, keys);
return set;
}
private String getCheckParams(boolean isDownload) { private String getCheckParams(boolean isDownload) {
return isDownload ? "com.arialyy.aria.core.download.DownloadTask" return isDownload ? "com.arialyy.aria.core.download.DownloadTask"
: "com.arialyy.aria.core.upload.UploadTask"; : "com.arialyy.aria.core.upload.UploadTask";

@ -35,4 +35,25 @@ public interface ProxyConstance {
*/ */
String UPLOAD_PROXY_CLASS_SUFFIX = "$$UploadListenerProxy"; String UPLOAD_PROXY_CLASS_SUFFIX = "$$UploadListenerProxy";
int DOWNLOAD_PRE = 0X11;
int DOWNLOAD_TASK_PRE = 0X12;
int DOWNLOAD_TASK_RESUME = 0X13;
int DOWNLOAD_TASK_START = 0X14;
int DOWNLOAD_TASK_STOP = 0X15;
int DOWNLOAD_TASK_CANCEL = 0X16;
int DOWNLOAD_TASK_FAIL = 0X17;
int DOWNLOAD_TASK_COMPLETE = 0X18;
int DOWNLOAD_TASK_RUNNING = 0X19;
int DOWNLOAD_TASK_NO_SUPPORT_BREAKPOINT = 0X1A;
int UPLOAD_PRE = 0X11;
int UPLOAD_TASK_PRE = 0X12;
int UPLOAD_TASK_RESUME = 0X13;
int UPLOAD_TASK_START = 0X14;
int UPLOAD_TASK_STOP = 0X15;
int UPLOAD_TASK_CANCEL = 0X16;
int UPLOAD_TASK_FAIL = 0X17;
int UPLOAD_TASK_COMPLETE = 0X18;
int UPLOAD_TASK_RUNNING = 0X19;
int UPLOAD_TASK_NO_SUPPORT_BREAKPOINT = 0X1A;
} }

@ -18,6 +18,7 @@ package com.arialyy.compiler;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set;
/** /**
* Created by Aria.Lao on 2017/6/7. * Created by Aria.Lao on 2017/6/7.
@ -27,6 +28,6 @@ class ProxyEntity {
public String packageName; public String packageName;
public String className; public String className;
public boolean isDownlaod = true; public boolean isDownlaod = true;
public Map<String, Set<String>> keyMappings = new HashMap<>();
public Map<Class<? extends Annotation>, String> methods = new HashMap<>(); public Map<Class<? extends Annotation>, String> methods = new HashMap<>();
} }

@ -27,8 +27,13 @@ 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/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) [![Download](https://api.bintray.com/packages/arialyy/maven/AriaCompiler/images/download.svg)](https://bintray.com/arialyy/maven/AriaCompiler/_latestVersion)
```java ```java
<<<<<<< HEAD
compile 'com.arialyy.aria:aria-core:3.1.8' compile 'com.arialyy.aria:aria-core:3.1.8'
annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8' annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8'
=======
compile 'com.arialyy.aria:Aria:3.1.9'
annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.9'
>>>>>>> v_3.0
``` ```
## 示例 ## 示例
@ -81,8 +86,14 @@ annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8'
``` ```
### 下载状态获取 ### 下载状态获取
<<<<<<< HEAD
如果你希望读取下载进度或下载信息,那么你需要 如果你希望读取下载进度或下载信息,那么你需要
* 将对象注册到Aria * 将对象注册到Aria
=======
如果你希望读取下载进度或下载信息,那么你需要创建事件类,并在onResume(Activity、Fragment)或构造函数(Dialog、PopupWindow),将该事件类注册到Aria管理器。
1. 将对象注册到Aria
>>>>>>> v_3.0
`Aria.download(this).register();`或`Aria.upload(this).register();` `Aria.download(this).register();`或`Aria.upload(this).register();`
```java ```java
@ -93,7 +104,11 @@ annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8'
} }
``` ```
<<<<<<< HEAD
* 使用`@Download`或`@Upload`注解你的函数 * 使用`@Download`或`@Upload`注解你的函数
=======
2. 使用`@Download`或`@Upload`注解你的函数
>>>>>>> v_3.0
**注意:** **注意:**
- 注解回掉采用Apt的方式实现,所以,你不需要担心这会影响你机器的性能 - 注解回掉采用Apt的方式实现,所以,你不需要担心这会影响你机器的性能
@ -101,18 +116,14 @@ annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8'
- 被注解的方法**只能有一个参数,并且参数类型必须是`DownloadTask`或`UploadTask`** - 被注解的方法**只能有一个参数,并且参数类型必须是`DownloadTask`或`UploadTask`**
- 方法名可以为任意字符串 - 方法名可以为任意字符串
* 除了在widget(Activity、Fragment、Dialog、Popupwindow)中使用注解方法外,你还可以在Service、Notification等组件中使用注解函数。 3. 除了在widget(Activity、Fragment、Dialog、Popupwindow)中使用注解方法外,你还可以在Service、Notification等组件中使用注解函数。
```java ```java
@Download.onPre @Download.onPre(DOWNLOAD_URL)
protected void onPre(DownloadTask task) {} protected void onPre(DownloadTask task) {}
@Download.onTaskStart @Download.onTaskStart
void taskStart(DownloadTask task) { void taskStart(DownloadTask task) {}
//通过下载地址可以判断任务是否是你指定的任务
if (task.getKey().equals(DOWNLOAD_URL)) {
}
}
@Download.onTaskRunning @Download.onTaskRunning
protected void running(DownloadTask task) {} protected void running(DownloadTask task) {}
@ -136,6 +147,19 @@ annotationProcessor 'com.arialyy.aria:aria-compiler:3.1.8'
public void onNoSupportBreakPoint(DownloadTask task) {} public void onNoSupportBreakPoint(DownloadTask task) {}
``` ```
4. 如果你希望对单个任务,或某一些特定任务设置监听器。
在注解中添加任务的下载地址,**则表示只有该任务才会触发被注解的方法**。
```java
@Download.onTaskRunning({
"https://test.xx.apk",
"http://test.xx2.apk"
}) void taskRunning(DownloadTask task) {
mAdapter.setProgress(task.getDownloadEntity());
}
```
在上面的例子中,只有下载地址是`https://test.xx.apk`和`http://test.xx2.apk`才会触发
`taskRunning(DownloadTask task)`方法。
### Aria参数配置 ### Aria参数配置
#### 配置文件设置参数 #### 配置文件设置参数
@ -218,21 +242,30 @@ Aria.get(this).getDownloadConfig().setMaxTaskNum(3);
```java ```java
Aria.download(this).stopAllTask(); Aria.download(this).stopAllTask();
``` ```
* 恢复所有停止的任务
```java
Aria.download(this).resumeAllTask();
```
* 删除所有任务 * 删除所有任务
```java ```java
Aria.download(this).removeAllTask(); Aria.download(this).removeAllTask();
``` ```
* 获取当前任务的下载速度 * 获取当前任务的下载速度
速度参数有点特殊,需要[下载事件支持](#下载状态获取) 速度参数有点特殊,需要[下载事件支持](#下载状态获取)
``` java ``` java
@Override public void onTaskRunning(DownloadTask task) { @Override public void onTaskRunning(DownloadTask task) {
//如果你打开了速度单位转换配置,将可以通过以下方法获取带单位的下载速度,如:1 m/s //如果你打开了速度单位转换配置,将可以通过以下方法获取带单位的下载速度,如:1 mb/s
String convertSpeed = task.getConvertSpeed(); String convertSpeed = task.getConvertSpeed();
//如果你有自己的单位格式,可以通过以下方法获取原始byte长度 //如果你有自己的单位格式,可以通过以下方法获取原始byte长度
long speed = task.getSpeed(); long speed = task.getSpeed();
} }
``` ```
* 获取下载的文件大小、当前进度百分比 * 获取下载的文件大小、当前进度百分比
同样的,你也可以在DownloadTask对象中获取下载的文件大小 同样的,你也可以在DownloadTask对象中获取下载的文件大小
``` ```
@ -245,6 +278,7 @@ Aria.download(this).removeAllTask();
int percent = task.getPercent(); int percent = task.getPercent();
} }
``` ```
* 设置高优先级任务 * 设置高优先级任务
如果你希望优先下载某一个任务,你可以 如果你希望优先下载某一个任务,你可以
``` java ``` java
@ -258,8 +292,6 @@ tip: 如果你数据比较多,或者数据比较复杂,你可以先把数据
Aria.download(this).load(DOWNLOAD_URL).setExtendField(str) Aria.download(this).load(DOWNLOAD_URL).setExtendField(str)
``` ```
**tips:为了防止内存泄露的情况,事件类需要使用staic进行修饰**
## 上传 ## 上传
* 添加任务(只添加,不上传) * 添加任务(只添加,不上传)
@ -310,6 +342,7 @@ Aria.download(this).load(DOWNLOAD_URL).setExtendField(str)
## 开发日志 ## 开发日志
+ v_3.1.9 修复stopAll队列没有任务时崩溃的问题,增加针对单个任务监听的功能
+ v_3.1.7 修复某些文件下载不了的bug,增加apt注解方法,事件获取更加简单了 + v_3.1.7 修复某些文件下载不了的bug,增加apt注解方法,事件获取更加简单了
+ v_3.1.6 取消任务时onTaskCancel回调两次的bug + v_3.1.6 取消任务时onTaskCancel回调两次的bug
+ v_3.1.5 优化代码结构,增加优先下载任务功能。 + v_3.1.5 优化代码结构,增加优先下载任务功能。

@ -30,6 +30,7 @@
<activity android:name=".download.fragment_download.FragmentActivity"/> <activity android:name=".download.fragment_download.FragmentActivity"/>
<activity android:name=".download.multi_download.MultiDownloadActivity"/> <activity android:name=".download.multi_download.MultiDownloadActivity"/>
<activity android:name=".download.HighestPriorityActivity"/> <activity android:name=".download.HighestPriorityActivity"/>
<activity android:name=".test.TestMutilTaskSysDownload"/>
<service android:name=".download.service_download.DownloadService"/> <service android:name=".download.service_download.DownloadService"/>
</application> </application>

@ -4,7 +4,7 @@
<!--注意,修改该配置文件中的属性会覆盖代码中所设置的属性--> <!--注意,修改该配置文件中的属性会覆盖代码中所设置的属性-->
<download> <download>
<!--设置下载线程,线程下载数改变后,新的下载任务才会生效--> <!--设置下载线程,线程下载数改变后,新的下载任务才会生效,如果任务大小小于1m,该设置也不会生效-->
<threadNum value="4"/> <threadNum value="4"/>
<!--是否打开下载广播,默认为false,不建议使用广播,你可以使用Download注解来实现事件回调--> <!--是否打开下载广播,默认为false,不建议使用广播,你可以使用Download注解来实现事件回调-->
@ -20,7 +20,7 @@
<reTryInterval value="5000"/> <reTryInterval value="5000"/>
<!--设置url连接超时时间,单位为毫秒,默认5000毫秒--> <!--设置url连接超时时间,单位为毫秒,默认5000毫秒-->
<connectTimeOut value="5000"/> <connectTimeOut value="10000"/>
<!--设置IO流读取时间,单位为毫秒,默认20000毫秒,该时间不能少于10000毫秒--> <!--设置IO流读取时间,单位为毫秒,默认20000毫秒,该时间不能少于10000毫秒-->
<iOTimeOut value="20000"/> <iOTimeOut value="20000"/>

@ -26,6 +26,7 @@ import com.arialyy.aria.core.Aria;
import com.arialyy.simple.base.BaseActivity; import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivityMainBinding; import com.arialyy.simple.databinding.ActivityMainBinding;
import com.arialyy.simple.download.DownloadActivity; import com.arialyy.simple.download.DownloadActivity;
import com.arialyy.simple.test.TestMutilTaskSysDownload;
import com.arialyy.simple.upload.UploadActivity; import com.arialyy.simple.upload.UploadActivity;
/** /**
@ -51,4 +52,8 @@ public class MainActivity extends BaseActivity<ActivityMainBinding> {
@OnClick(R.id.upload) public void uploadDemo() { @OnClick(R.id.upload) public void uploadDemo() {
startActivity(new Intent(this, UploadActivity.class)); startActivity(new Intent(this, UploadActivity.class));
} }
@OnClick(R.id.multi_test) public void mutliTest() {
startActivity(new Intent(this, TestMutilTaskSysDownload.class));
}
} }

@ -182,64 +182,47 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
return true; return true;
} }
@Download.onPre protected void onPre(DownloadTask task) { @Download.onPre(DOWNLOAD_URL) protected void onPre(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize()) mUpdateHandler.obtainMessage(DOWNLOAD_PRE, task.getDownloadEntity().getFileSize())
.sendToTarget(); .sendToTarget();
} }
}
@Download.onTaskStart void taskStart(DownloadTask task) { @Download.onTaskStart(DOWNLOAD_URL) void taskStart(DownloadTask task) {
//通过下载地址可以判断任务是否是你指定的任务
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.obtainMessage(DOWNLOAD_START, task.getDownloadEntity().getFileSize()) mUpdateHandler.obtainMessage(DOWNLOAD_START, task.getDownloadEntity().getFileSize())
.sendToTarget(); .sendToTarget();
} }
}
@Download.onTaskRunning protected void running(DownloadTask task) { @Download.onTaskRunning(DOWNLOAD_URL) protected void running(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.obtainMessage(DOWNLOAD_RUNNING, task).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_RUNNING, task).sendToTarget();
} }
}
@Download.onTaskResume void taskResume(DownloadTask task) { @Download.onTaskResume(DOWNLOAD_URL) void taskResume(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.obtainMessage(DOWNLOAD_START, task.getFileSize()).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_START, task.getFileSize()).sendToTarget();
} }
}
@Download.onTaskStop void taskStop(DownloadTask task) { @Download.onTaskStop(DOWNLOAD_URL) void taskStop(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.sendEmptyMessage(DOWNLOAD_STOP); mUpdateHandler.sendEmptyMessage(DOWNLOAD_STOP);
L.d(TAG, "task__stop"); L.d(TAG, "task__stop");
} }
}
@Download.onTaskCancel void taskCancel(DownloadTask task) { @Download.onTaskCancel(DOWNLOAD_URL) void taskCancel(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.sendEmptyMessage(DOWNLOAD_CANCEL); mUpdateHandler.sendEmptyMessage(DOWNLOAD_CANCEL);
L.d(TAG, "task__cancel"); L.d(TAG, "task__cancel");
} }
}
@Download.onTaskFail void taskFail(DownloadTask task) { @Download.onTaskFail(DOWNLOAD_URL) void taskFail(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) { L.d(TAG, "task__fail");
mUpdateHandler.sendEmptyMessage(DOWNLOAD_FAILE); mUpdateHandler.sendEmptyMessage(DOWNLOAD_FAILE);
} }
}
@Download.onTaskComplete void taskComplete(DownloadTask task) { @Download.onTaskComplete(DOWNLOAD_URL) void taskComplete(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mUpdateHandler.sendEmptyMessage(DOWNLOAD_COMPLETE); mUpdateHandler.sendEmptyMessage(DOWNLOAD_COMPLETE);
} }
}
@Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) { @Download.onNoSupportBreakPoint(DOWNLOAD_URL)
if (task.getKey().equals(DOWNLOAD_URL)) { public void onNoSupportBreakPoint(DownloadTask task) {
T.showShort(SingleTaskActivity.this, "该下载链接不支持断点"); T.showShort(SingleTaskActivity.this, "该下载链接不支持断点");
} }
}
@Override protected int setLayoutId() { @Override protected int setLayoutId() {
return R.layout.activity_single; return R.layout.activity_single;

@ -16,6 +16,7 @@
package com.arialyy.simple.download.fragment_download; package com.arialyy.simple.download.fragment_download;
import android.os.Bundle;
import com.arialyy.simple.R; import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity; import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.FragmentDownloadBinding; import com.arialyy.simple.databinding.FragmentDownloadBinding;
@ -28,4 +29,9 @@ public class FragmentActivity extends BaseActivity<FragmentDownloadBinding> {
@Override protected int setLayoutId() { @Override protected int setLayoutId() {
return R.layout.activity_fragment; return R.layout.activity_fragment;
} }
@Override protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
setTile("Fragment 中使用");
}
} }

@ -24,6 +24,7 @@ import android.widget.TextView;
import butterknife.Bind; import butterknife.Bind;
import com.arialyy.aria.core.Aria; import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.simple.R; import com.arialyy.simple.R;
import com.arialyy.simple.base.adapter.AbsHolder; import com.arialyy.simple.base.adapter.AbsHolder;
@ -152,8 +153,8 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
} }
private String covertCurrentSize(long currentSize) { private String covertCurrentSize(long currentSize) {
String size = CommonUtil.formatFileSize(currentSize); if (currentSize < 0) return "0";
return size.substring(0, size.length() - 2); return CommonUtil.formatFileSize(currentSize);
} }
private int getColor(int color) { private int getColor(int color) {

@ -20,12 +20,15 @@ import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import butterknife.Bind; import butterknife.Bind;
import com.arialyy.annotations.Download; import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria; import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.frame.util.show.L; import com.arialyy.frame.util.show.L;
import com.arialyy.frame.util.show.T;
import com.arialyy.simple.R; import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity; import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivityMultiDownloadBinding; import com.arialyy.simple.databinding.ActivityMultiDownloadBinding;
@ -35,12 +38,16 @@ import java.util.List;
/** /**
* Created by AriaL on 2017/1/6. * Created by AriaL on 2017/1/6.
*/ */
public class MultiDownloadActivity extends BaseActivity<ActivityMultiDownloadBinding> { public class MultiDownloadActivity extends BaseActivity<ActivityMultiDownloadBinding> {
@Bind(R.id.list) RecyclerView mList; @Bind(R.id.list) RecyclerView mList;
private DownloadAdapter mAdapter; private DownloadAdapter mAdapter;
private List<DownloadEntity> mData = new ArrayList<>(); private List<DownloadEntity> mData = new ArrayList<>();
String[] mFilterStr = new String[] {
"https://g37.gdl.netease.com/onmyoji_netease_10_1.0.20.apk",
"http://static.gaoshouyou.com/d/eb/f2/dfeba30541f209ab8a50d847fc1661ce.apk"
};
@Override protected int setLayoutId() { @Override protected int setLayoutId() {
return R.layout.activity_multi_download; return R.layout.activity_multi_download;
} }
@ -58,6 +65,16 @@ public class MultiDownloadActivity extends BaseActivity<ActivityMultiDownloadBin
mList.setAdapter(mAdapter); mList.setAdapter(mAdapter);
} }
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_mutil_task, menu);
return super.onCreateOptionsMenu(menu);
}
@Override public boolean onMenuItemClick(MenuItem item) {
Aria.download(this).resumeAllTask();
return true;
}
@Download.onPre void onPre(DownloadTask task) { @Download.onPre void onPre(DownloadTask task) {
L.d(TAG, "download onPre"); L.d(TAG, "download onPre");
mAdapter.updateState(task.getDownloadEntity()); mAdapter.updateState(task.getDownloadEntity());
@ -82,14 +99,17 @@ public class MultiDownloadActivity extends BaseActivity<ActivityMultiDownloadBin
} }
@Download.onTaskFail void taskFail(DownloadTask task) { @Download.onTaskFail void taskFail(DownloadTask task) {
L.d(TAG, "download fail"); mAdapter.updateState(task.getDownloadEntity());
} }
@Download.onTaskComplete void taskComplete(DownloadTask task) { @Download.onTaskComplete void taskComplete(DownloadTask task) {
mAdapter.updateState(task.getDownloadEntity()); mAdapter.updateState(task.getDownloadEntity());
} }
@Download.onTaskRunning void taskRunning(DownloadTask task) { @Download.onTaskRunning({
"https://g37.gdl.netease.com/onmyoji_netease_10_1.0.20.apk",
"http://static.gaoshouyou.com/d/eb/f2/dfeba30541f209ab8a50d847fc1661ce.apk"
}) void taskRunning(DownloadTask task) {
mAdapter.setProgress(task.getDownloadEntity()); mAdapter.setProgress(task.getDownloadEntity());
} }
} }

@ -0,0 +1,74 @@
package com.arialyy.simple.test;
import android.os.Environment;
import android.view.View;
import com.arialyy.aria.core.Aria;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.TestActivityMultiBinding;
/**
* Created by AriaL on 2017/6/15.
*/
public class TestMutilTaskSysDownload extends BaseActivity<TestActivityMultiBinding> {
@Override protected int setLayoutId() {
return R.layout.test_activity_multi;
}
public void onClick(View view) {
String baseUrl = "http://file.bmob.cn/";
String[] urlArray = {
"M02/3B/A4/oYYBAFaOeUSAc1QiAAFTbmA7AHs052.jpg",
"M02/3B/A4/oYYBAFaOeUaAfYC-AAFD8zf9NXc879.jpg",
"M02/3B/A4/oYYBAFaOeUuAOxhnAACSdmbqSac702.jpg",
"M02/3B/A4/oYYBAFaOeU2AFAIGAAFICximvXc924.jpg",
"M02/3B/A4/oYYBAFaOeVCAPWMQAAFm2KWCq_E721.jpg",
"M02/3B/A4/oYYBAFaOeVOAbiv9AAFfCTTgr94948.jpg",
"M02/3B/A4/oYYBAFaOeVaAMR3tAAFf3yTuuCM577.jpg",
"M02/3B/A4/oYYBAFaOeVmACEWhAAEt72ecbpg468.jpg",
"M02/3B/A4/oYYBAFaOeVyAHHt4AAFg9e9bRio507.jpg",
"M02/3B/A4/oYYBAFaOeV-AClYXAAESLGY0gag424.jpg",
"M02/3B/A4/oYYBAFaOeWKAA7N0AAF3omYOJUI703.jpg",
"M02/3B/A4/oYYBAFaOeWWAD2lrAAFN7eRFxBs575.jpg",
"M02/3B/A4/oYYBAFaOeWiAdCVEAAFg4273Dus313.jpg",
"M02/3B/A4/oYYBAFaOeWyAJDm5AAF8JVoGVb0705.jpg",
"M02/3B/A4/oYYBAFaOeW-AUoA8AAGjKiHkXUo181.jpg",
"M02/3B/A4/oYYBAFaOeXKABIamAAFU7J7vraE265.jpg",
"M02/3B/A5/oYYBAFaOeXaAW09jAAFf37qdwDA457.jpg",
"M02/3B/A5/oYYBAFaOeXmAWmS7AAFtLNpWjgo967.jpg",
"M02/3B/A5/oYYBAFaOeX2AQf9cAAF2fhwS2UE145.jpg",
"M02/3B/A5/oYYBAFaOeYCAKGnLAAFVAzks-qU937.jpg",
"M02/3B/A5/oYYBAFaOeYOAMODNAAF6HjTTMq4819.jpg",
"M02/3B/A5/oYYBAFaOeYeAbn8uAAFLSQLw48Q042.jpg",
"M02/3B/A5/oYYBAFaOeYqAMJThAAFtrNe4UNM047.jpg",
"M02/3B/A5/oYYBAFaOeY2AbnQvAAFNSXWn0Dc026.jpg",
"M02/3B/A5/oYYBAFaOeZCAIsr0AAFHZFEVhPc682.jpg",
"M02/3B/A5/oYYBAFaOeZOAGvITAAFqPmfcc9c471.jpg",
"M02/3B/A5/oYYBAFaOeZaATvjbAAFHDmALnhE003.jpg",
"M02/3B/A5/oYYBAFaOeZmAJPuVAAFfPJC2wsE319.jpg",
"M02/3B/A5/oYYBAFaOeZyAXtAmAAFfArJNwtM371.jpg",
"M02/3B/A5/oYYBAFaOeZ-AGZN0AAFgqwYYCS8004.jpg",
"M02/3B/A5/oYYBAFaOeaOAbbrGAAFcq59JjUo205.jpg",
"M02/3B/A5/oYYBAFaOeaSAdFyoAACaxVxgUJA092.jpg"
};
int maxNum = Aria.get(this).getDownloadConfig().getMaxTaskNum();
for (int i = 0; i < urlArray.length; i++) {
if (i < maxNum) {
Aria.download(this)
.load(baseUrl + urlArray[i])
.setDownloadPath(Environment.getExternalStorageDirectory() + "/test/" + i + ".jpg")
//.addHeader("Accept-Encoding", "gzip,deflate,sdcn")
.start();
} else {
Aria.download(this)
.load(baseUrl + urlArray[i])
.setDownloadPath(Environment.getExternalStorageDirectory() + "/test/" + i + ".jpg")
//.addHeader("Accept-Encoding", "gzip,deflate,sdcn")
.add();
}
}
}
}

@ -6,6 +6,7 @@
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical" android:orientation="vertical"
> >
<include layout="@layout/layout_bar"/>
<fragment <fragment
android:id="@+id/fragment1" android:id="@+id/fragment1"
android:name="com.arialyy.simple.download.fragment_download.DownloadFragment" android:name="com.arialyy.simple.download.fragment_download.DownloadFragment"

@ -24,5 +24,14 @@
android:text="上传 demo" android:text="上传 demo"
style="?buttonBarButtonStyle" style="?buttonBarButtonStyle"
/> />
<Button
android:id="@+id/multi_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="多任务测试"
style="?buttonBarButtonStyle"
/>
</LinearLayout> </LinearLayout>
</layout> </layout>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include layout="@layout/layout_bar"/>
<Button
android:onClick="onClick"
android:id="@+id/download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="多任务同时下载"
style="?buttonBarButtonStyle"
/>
</LinearLayout>
</layout>

@ -7,9 +7,8 @@
android:icon="@mipmap/ic_add_black_48dp" android:icon="@mipmap/ic_add_black_48dp"
android:orderInCategory="80" android:orderInCategory="80"
android:title="添加一组任务" android:title="添加一组任务"
app:showAsAction="ifRoom" app:showAsAction="always"
/> />
<item <item
android:id="@+id/help" android:id="@+id/help"
android:icon="@mipmap/ic_help_black_48dp" android:icon="@mipmap/ic_help_black_48dp"

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/resume_all"
android:orderInCategory="80"
android:title="resume_all_task"
app:showAsAction="always"
/>
</menu>

@ -37,7 +37,7 @@ ext {
userOrg = 'arialyy' userOrg = 'arialyy'
groupId = 'com.arialyy.aria' groupId = 'com.arialyy.aria'
// publishVersion = '0.0.6' // publishVersion = '0.0.6'
publishVersion = '3.1.8' publishVersion = '3.1.9'
repoName='maven' repoName='maven'
desc = 'android 下载框架' desc = 'android 下载框架'
website = 'https://github.com/AriaLyy/Aria' website = 'https://github.com/AriaLyy/Aria'

@ -4,3 +4,4 @@ distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip
#distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

Loading…
Cancel
Save