Merge branch 'v_3.0'

pull/330/head 3.1.0
AriaLyy 8 years ago
commit 3fb93080b1
  1. 4
      Aria/build.gradle
  2. 139
      Aria/src/main/java/com/arialyy/aria/core/AriaManager.java
  3. 234
      Aria/src/main/java/com/arialyy/aria/core/ConfigHelper.java
  4. 267
      Aria/src/main/java/com/arialyy/aria/core/Configuration.java
  5. 14
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadEntity.java
  6. 6
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadStateConstance.java
  7. 100
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadTask.java
  8. 100
      Aria/src/main/java/com/arialyy/aria/core/download/DownloadUtil.java
  9. 105
      Aria/src/main/java/com/arialyy/aria/core/download/SingleThreadTask.java
  10. 8
      Aria/src/main/java/com/arialyy/aria/core/inf/ITask.java
  11. 1
      Aria/src/main/java/com/arialyy/aria/core/queue/AbsTaskQueue.java
  12. 5
      Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java
  13. 6
      Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java
  14. 3
      Aria/src/main/java/com/arialyy/aria/core/queue/UploadTaskQueue.java
  15. 11
      Aria/src/main/java/com/arialyy/aria/core/queue/pool/ExecutePool.java
  16. 17
      Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java
  17. 16
      Aria/src/main/java/com/arialyy/aria/core/scheduler/UploadSchedulers.java
  18. 11
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadEntity.java
  19. 137
      Aria/src/main/java/com/arialyy/aria/core/upload/UploadTask.java
  20. 228
      Aria/src/main/java/com/arialyy/aria/util/Configuration_1.java
  21. 173
      Aria/src/main/java/com/arialyy/aria/util/FileUtil.java
  22. 113
      Aria/src/main/java/com/arialyy/aria/util/ReflectionUtil.java
  23. 137
      README.md
  24. 18
      app/src/main/assets/aria_config.xml
  25. 1
      app/src/main/java/com/arialyy/simple/MainActivity.java
  26. 8
      app/src/main/java/com/arialyy/simple/download/DownloadDialog.java
  27. 2
      app/src/main/java/com/arialyy/simple/download/DownloadPopupWindow.java
  28. 60
      app/src/main/java/com/arialyy/simple/download/SingleTaskActivity.java
  29. 5
      app/src/main/java/com/arialyy/simple/download/fragment_download/DownloadFragment.java
  30. 7
      app/src/main/java/com/arialyy/simple/download/multi_download/DownloadAdapter.java
  31. 2
      app/src/main/java/com/arialyy/simple/download/multi_download/MultiTaskActivity.java
  32. 6
      app/src/main/java/com/arialyy/simple/download/service_download/DownloadService.java
  33. 2
      app/src/main/res/values/strings.xml
  34. 4
      gradle.properties

@ -7,8 +7,8 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 9 minSdkVersion 9
targetSdkVersion 23 targetSdkVersion 23
versionCode 102 versionCode 310
versionName "3.0.3" versionName "3.1.0"
} }
buildTypes { buildTypes {
release { release {

@ -31,17 +31,20 @@ import android.widget.PopupWindow;
import com.arialyy.aria.core.download.DownloadReceiver; import com.arialyy.aria.core.download.DownloadReceiver;
import com.arialyy.aria.core.inf.ICmd; import com.arialyy.aria.core.inf.ICmd;
import com.arialyy.aria.core.inf.IReceiver; import com.arialyy.aria.core.inf.IReceiver;
import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.upload.UploadReceiver; import com.arialyy.aria.core.upload.UploadReceiver;
import com.arialyy.aria.orm.DbUtil; import com.arialyy.aria.orm.DbUtil;
import com.arialyy.aria.util.CAConfiguration; import com.arialyy.aria.util.FileUtil;
import com.arialyy.aria.util.Configuration_1; import java.io.File;
import com.arialyy.aria.util.Speed; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
/** /**
* Created by lyy on 2016/12/1. * Created by lyy on 2016/12/1.
@ -57,12 +60,14 @@ import java.util.Map;
private Map<String, IReceiver> mReceivers = new HashMap<>(); private Map<String, IReceiver> mReceivers = new HashMap<>();
public static Context APP; public static Context APP;
private List<ICmd> mCommands = new ArrayList<>(); private List<ICmd> mCommands = new ArrayList<>();
private Configuration mConfig; private Configuration.DownloadConfig mDConfig;
private Configuration.UploadConfig mUConfig;
private AriaManager(Context context) { private AriaManager(Context context) {
DbUtil.init(context.getApplicationContext()); DbUtil.init(context.getApplicationContext());
APP = context.getApplicationContext(); APP = context.getApplicationContext();
regAppLifeCallback(context); regAppLifeCallback(context);
initConfig();
} }
public static AriaManager getInstance(Context context) { public static AriaManager getInstance(Context context) {
@ -79,10 +84,43 @@ import java.util.Map;
} }
/** /**
* 设置最大下载速度 * 加载配置文件
*/ */
public void setMaxSpeed(Speed speed) { private void loadConfig() {
Configuration_1.getInstance().setMaxSpeed(speed); try {
ConfigHelper helper = new ConfigHelper();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(APP.getAssets().open("aria_config.xml"), helper);
} catch (ParserConfigurationException | IOException | SAXException e) {
Log.e(TAG, e.toString());
}
}
/**
* 如果需要在代码中修改下载配置请使用以下方法
* <pre>
* <code>
* //修改最大任务队列数
* Aria.get(this).getDownloadConfig().setMaxTaskNum(3);
* </code>
* </pre>
*/
public Configuration.DownloadConfig getDownloadConfig() {
return mDConfig;
}
/**
* 如果需要在代码中修改下载配置请使用以下方法
* <pre>
* <code>
* //修改最大任务队列数
* Aria.get(this).getUploadConfig().setMaxTaskNum(3);
* </code>
* </pre>
*/
public Configuration.UploadConfig getUploadConfig() {
return mUConfig;
} }
/** /**
@ -135,70 +173,6 @@ import java.util.Map;
return (receiver instanceof UploadReceiver) ? (UploadReceiver) receiver : null; return (receiver instanceof UploadReceiver) ? (UploadReceiver) receiver : null;
} }
/**
* 设置CA证书信息
*
* @param caAlias ca证书别名
* @param caPath assets 文件夹下的ca证书完整路径
*/
public void setCAInfo(String caAlias, String caPath) {
if (TextUtils.isEmpty(caAlias)) {
Log.e(TAG, "ca证书别名不能为null");
return;
} else if (TextUtils.isEmpty(caPath)) {
Log.e(TAG, "ca证书路径不能为null");
return;
}
CAConfiguration.CA_ALIAS = caAlias;
CAConfiguration.CA_PATH = caPath;
}
/**
* 设置下载超时时间
*/
@Deprecated private AriaManager setTimeOut(int timeOut) {
Configuration_1.getInstance().setTimeOut(timeOut);
return this;
}
/**
* 设置失败重试次数
*/
public AriaManager setReTryNum(int reTryNum) {
Configuration_1.getInstance().setReTryNum(reTryNum);
return this;
}
/**
* 设置失败重试间隔
*/
public AriaManager setReTryInterval(int interval) {
Configuration_1.getInstance().setReTryInterval(interval);
return this;
}
/**
* 是否打开下载广播
*/
public AriaManager openBroadcast(boolean open) {
Configuration_1.getInstance().setOpenBroadcast(open);
return this;
}
/**
* 设置最大下载数最大下载数不能小于1
*
* @param maxDownloadNum 最大下载数
*/
public AriaManager setMaxDownloadNum(int maxDownloadNum) {
if (maxDownloadNum < 1) {
Log.w(TAG, "最大任务数不能小于 1");
return this;
}
DownloadTaskQueue.getInstance().setDownloadNum(maxDownloadNum);
return this;
}
private IReceiver putReceiver(boolean isDownload, Object obj) { private IReceiver putReceiver(boolean isDownload, Object obj) {
final String key = getKey(isDownload, obj); final String key = getKey(isDownload, obj);
IReceiver receiver = mReceivers.get(key); IReceiver receiver = mReceivers.get(key);
@ -268,6 +242,27 @@ import java.util.Map;
return key; return key;
} }
/**
* 初始化配置文件
*/
private void initConfig() {
File xmlFile = new File(APP.getFilesDir().getPath() + Configuration.XML_FILE);
if (!xmlFile.exists()) {
loadConfig();
} else {
try {
String md5Code = FileUtil.getFileMD5(xmlFile);
if (!FileUtil.checkMD5(md5Code, APP.getAssets().open("aria_config.xml"))) {
loadConfig();
}
} catch (IOException e) {
e.printStackTrace();
}
}
mDConfig = Configuration.DownloadConfig.getInstance();
mUConfig = Configuration.UploadConfig.getInstance();
}
/** /**
* 注册APP生命周期回调 * 注册APP生命周期回调
*/ */

@ -0,0 +1,234 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core;
import android.text.TextUtils;
import android.util.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Created by Aria.Lao on 2017/5/22.
* 读取配置文件
*/
public class ConfigHelper extends DefaultHandler {
private final String TAG = "ConfigHelper";
private boolean isDownloadConfig = false, isUploadConfig;
private Configuration.DownloadConfig mDownloadConfig = Configuration.DownloadConfig.getInstance();
private Configuration.UploadConfig mUploadConfig = Configuration.UploadConfig.getInstance();
@Override public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (qName.equals("download")) {
isDownloadConfig = true;
isUploadConfig = false;
} else if (qName.equals("upload")) {
isUploadConfig = true;
isDownloadConfig = false;
}
if (isDownloadConfig || isUploadConfig) {
String value = attributes.getValue("value");
switch (qName) {
case "threadNum":
loadThreadNum(value);
break;
case "openBroadcast":
loadBroadcast(value);
break;
case "maxTaskNum":
loadMaxQueue(value);
break;
case "reTryNum":
loadReTry(value);
break;
case "connectTimeOut":
loadConnectTime(value);
break;
case "iOTimeOut":
loadIOTimeout(value);
break;
case "reTryInterval":
loadReTryInterval(value);
break;
case "buffSize":
loadBuffSize(value);
break;
case "ca":
String caName = attributes.getValue("name");
String caPath = attributes.getValue("path");
loadCA(caName, caPath);
break;
case "convertSpeed":
loadConvertSpeed(value);
break;
}
}
}
private void loadConvertSpeed(String value) {
boolean open = Boolean.parseBoolean(value);
if (isDownloadConfig) {
mDownloadConfig.isConvertSpeed = open;
}
if (isUploadConfig) {
mUploadConfig.isConvertSpeed = open;
}
}
private void loadReTryInterval(String value) {
int time = 2 * 1000;
if (!TextUtils.isEmpty(value)) {
time = Integer.parseInt(value);
}
if (time < 2 * 1000) {
time = 2 * 1000;
}
if (isDownloadConfig) {
mDownloadConfig.reTryInterval = time;
}
}
private void loadCA(String name, String path) {
if (isDownloadConfig) {
mDownloadConfig.caName = name;
mDownloadConfig.caPath = path;
}
}
private void loadBuffSize(String value) {
int buffSize = 8192;
if (!TextUtils.isEmpty(value)) {
buffSize = Integer.parseInt(value);
}
if (buffSize < 2048) {
buffSize = 2048;
}
if (isDownloadConfig) {
mDownloadConfig.buffSize = buffSize;
}
}
private void loadIOTimeout(String value) {
int time = 10 * 1000;
if (!TextUtils.isEmpty(value)) {
time = Integer.parseInt(value);
}
if (time < 10 * 1000) {
time = 10 * 1000;
}
if (isDownloadConfig) {
mDownloadConfig.iOTimeOut = time;
}
}
private void loadConnectTime(String value) {
int time = 5 * 1000;
if (!TextUtils.isEmpty(value)) {
time = Integer.parseInt(value);
}
if (isDownloadConfig) {
mDownloadConfig.connectTimeOut = time;
}
if (isUploadConfig) {
mUploadConfig.connectTimeOut = time;
}
}
private void loadReTry(String value) {
int num = 0;
if (!TextUtils.isEmpty(value)) {
num = Integer.parseInt(value);
}
if (isDownloadConfig) {
mDownloadConfig.reTryNum = num;
}
if (isUploadConfig) {
mUploadConfig.reTryNum = num;
}
}
private void loadMaxQueue(String value) {
int num = 2;
if (!TextUtils.isEmpty(value)) {
num = Integer.parseInt(value);
}
if (num < 1) {
Log.e(TAG, "任务队列数不能小于 1");
num = 2;
}
if (isDownloadConfig) {
mDownloadConfig.maxTaskNum = num;
}
if (isUploadConfig) {
mUploadConfig.maxTaskNum = num;
}
}
private void loadBroadcast(String value) {
boolean open = Boolean.parseBoolean(value);
if (isDownloadConfig) {
mDownloadConfig.isOpenBreadCast = open;
}
if (isUploadConfig) {
mUploadConfig.isOpenBreadCast = open;
}
}
private void loadThreadNum(String value) {
int num = 3;
if (!TextUtils.isEmpty(value)) {
num = Integer.parseInt(value);
}
if (num < 1) {
Log.e(TAG, "下载线程数不能小于 1");
num = 3;
}
if (isDownloadConfig) {
mDownloadConfig.threadNum = num;
}
}
@Override public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
}
@Override public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
}
@Override public void endDocument() throws SAXException {
super.endDocument();
mDownloadConfig.saveAll();
mUploadConfig.saveAll();
}
}

@ -15,36 +15,200 @@
*/ */
package com.arialyy.aria.core; package com.arialyy.aria.core;
import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.ReflectionUtil;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Properties;
/** /**
* Created by AriaL on 2016/12/8. * Created by AriaL on 2016/12/8.
* 信息配置 * 信息配置
*/ */
class Configuration { class Configuration {
private static final String TAG = "Configuration"; static final String DOWNLOAD_CONFIG_FILE = "/Aria/DownloadConfig.properties";
private static final String CONFIG_FILE = "/Aria/ADConfig.properties"; static final String UPLOAD_CONFIG_FILE = "/Aria/UploadConfig.properties";
private static final String CONFIG_KEY = "ARIA_CONFIG"; static final String XML_FILE = "/Aria/aria_config.xml";
/** /**
* 通用配置 * 通用配置
*/ */
static class BaseConfig { public static class BaseConfig {
public boolean isOpenBreadCast = false; /**
* 旧任务数
*/
public static int oldMaxTaskNum = 2;
/**
* 是否发送任务广播true发送
*/
boolean isOpenBreadCast = false;
/** /**
* 任务队列最大任务数 默认为2 * 任务队列最大任务数 默认为2
*/ */
public int maxQueueNum = 2; int maxTaskNum = 2;
/** /**
* 下载失败重试次数默认为10 * 下载失败重试次数默认为10
*/ */
public int reTryNum = 10; int reTryNum = 10;
/** /**
* 设置重试间隔单位为毫秒默认2000毫秒 * 设置重试间隔单位为毫秒默认2000毫秒
*/ */
public long reTryInterval = 2000; int reTryInterval = 2000;
/** /**
* 设置url连接超时时间单位为毫秒默认5000毫秒 * 设置url连接超时时间单位为毫秒默认5000毫秒
*/ */
public long connectTimeOut = 5000; int connectTimeOut = 5000;
/**
* 是否需要转换速度单位转换完成后为1b/s1k/s1m/s1g/s1t/s如果不需要将返回byte长度
*/
boolean isConvertSpeed = false;
public boolean isOpenBreadCast() {
return isOpenBreadCast;
}
public BaseConfig setOpenBreadCast(boolean openBreadCast) {
isOpenBreadCast = openBreadCast;
saveKey("isOpenBreadCast", openBreadCast + "");
return this;
}
public int getMaxTaskNum() {
return maxTaskNum;
}
public BaseConfig setMaxTaskNum(int maxTaskNum) {
oldMaxTaskNum = this.maxTaskNum;
this.maxTaskNum = maxTaskNum;
saveKey("maxTaskNum", maxTaskNum + "");
DownloadTaskQueue.getInstance().setDownloadNum(maxTaskNum);
return this;
}
public int getReTryNum() {
return reTryNum;
}
public BaseConfig setReTryNum(int reTryNum) {
this.reTryNum = reTryNum;
saveKey("reTryNum", reTryNum + "");
return this;
}
public int getReTryInterval() {
return reTryInterval;
}
public BaseConfig setReTryInterval(int reTryInterval) {
this.reTryInterval = reTryInterval;
saveKey("reTryInterval", reTryInterval + "");
return this;
}
public boolean isConvertSpeed() {
return isConvertSpeed;
}
public BaseConfig setConvertSpeed(boolean convertSpeed) {
isConvertSpeed = convertSpeed;
saveKey("isConvertSpeed", isConvertSpeed + "");
return this;
}
public int getConnectTimeOut() {
return connectTimeOut;
}
public BaseConfig setConnectTimeOut(int connectTimeOut) {
this.connectTimeOut = connectTimeOut;
saveKey("connectTimeOut", connectTimeOut + "");
return this;
}
/**
* 保存key
*/
void saveKey(String key, String value) {
boolean isDownload = this instanceof DownloadConfig;
File file = new File(
AriaManager.APP.getFilesDir().getPath() + (isDownload ? DOWNLOAD_CONFIG_FILE
: UPLOAD_CONFIG_FILE));
if (file.exists()) {
Properties properties = CommonUtil.loadConfig(file);
properties.setProperty(key, value);
CommonUtil.saveConfig(file, properties);
}
}
/**
* 加载配置
*/
void loadConfig() {
boolean isDownload = this instanceof DownloadConfig;
File file = new File(
AriaManager.APP.getFilesDir().getPath() + (isDownload ? DOWNLOAD_CONFIG_FILE
: UPLOAD_CONFIG_FILE));
if (file.exists()) {
Properties properties = CommonUtil.loadConfig(file);
List<Field> fields = ReflectionUtil.getAllFields(getClass());
try {
for (Field field : fields) {
int m = field.getModifiers();
if (Modifier.isFinal(m) || Modifier.isStatic(m)) {
continue;
}
field.setAccessible(true);
String value = properties.getProperty(field.getName());
Class<?> type = field.getType();
if (type == String.class) {
field.set(this, value);
} else if (type == int.class || type == Integer.class) {
field.setInt(this, Integer.parseInt(value));
} else if (type == float.class || type == Float.class) {
field.setFloat(this, Float.parseFloat(value));
} else if (type == double.class || type == Double.class) {
field.setDouble(this, Double.parseDouble(value));
} else if (type == long.class || type == Long.class) {
field.setLong(this, Long.parseLong(value));
} else if (type == boolean.class || type == Boolean.class) {
field.setBoolean(this, Boolean.parseBoolean(value));
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
/**
* 保存配置
*/
void saveAll() {
List<Field> fields = ReflectionUtil.getAllFields(getClass());
boolean isDownload = this instanceof DownloadConfig;
try {
File file = new File(
AriaManager.APP.getFilesDir().getPath() + (isDownload ? DOWNLOAD_CONFIG_FILE
: UPLOAD_CONFIG_FILE));
Properties properties = CommonUtil.loadConfig(file);
for (Field field : fields) {
int m = field.getModifiers();
if (Modifier.isFinal(m) || Modifier.isStatic(m)) {
continue;
}
field.setAccessible(true);
properties.setProperty(field.getName(), field.get(this) + "");
}
CommonUtil.saveConfig(file, properties);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} }
/** /**
@ -54,19 +218,82 @@ class Configuration {
/** /**
* 设置IO流读取时间单位为毫秒默认20000毫秒该时间不能少于10000毫秒 * 设置IO流读取时间单位为毫秒默认20000毫秒该时间不能少于10000毫秒
*/ */
public long readTimeout = 20 * 1000; int iOTimeOut = 20 * 1000;
/** /**
* 设置写文件buff大小该数值大小不能小于2048数值变小下载速度会变慢 * 设置写文件buff大小该数值大小不能小于2048数值变小下载速度会变慢
*/ */
public int buffSize = 8192; int buffSize = 8192;
/** /**
* 设置https ca 证书信息path 为assets目录下的CA证书完整路径 * 设置https ca 证书信息path 为assets目录下的CA证书完整路径
*/ */
public String caPath; String caPath;
/** /**
* name 为CA证书名 * name 为CA证书名
*/ */
public String caName; String caName;
/**
* 下载线程数下载线程数不能小于1
*/
int threadNum = 3;
public int getIOTimeOut() {
return iOTimeOut;
}
public DownloadConfig setIOTimeOut(int iOTimeOut) {
this.iOTimeOut = iOTimeOut;
saveKey("iOTimeOut", iOTimeOut + "");
return this;
}
public int getBuffSize() {
return buffSize;
}
public DownloadConfig setBuffSize(int buffSize) {
this.buffSize = buffSize;
saveKey("buffSize", buffSize + "");
return this;
}
public String getCaPath() {
return caPath;
}
public DownloadConfig setCaPath(String caPath) {
this.caPath = caPath;
saveKey("caPath", caPath);
return this;
}
public String getCaName() {
return caName;
}
public DownloadConfig setCaName(String caName) {
this.caName = caName;
saveKey("caName", caName);
return this;
}
public int getThreadNum() {
return threadNum;
}
private DownloadConfig() {
loadConfig();
}
private static DownloadConfig INSTANCE = null;
static DownloadConfig getInstance() {
if (INSTANCE == null) {
synchronized (DownloadConfig.class) {
INSTANCE = new DownloadConfig();
}
}
return INSTANCE;
}
} }
/** /**
@ -74,5 +301,19 @@ class Configuration {
*/ */
public static class UploadConfig extends BaseConfig { public static class UploadConfig extends BaseConfig {
private UploadConfig() {
loadConfig();
}
private static UploadConfig INSTANCE = null;
static UploadConfig getInstance() {
if (INSTANCE == null) {
synchronized (DownloadConfig.class) {
INSTANCE = new UploadConfig();
}
}
return INSTANCE;
}
} }
} }

@ -31,6 +31,7 @@ import com.arialyy.aria.orm.DbEntity;
*/ */
public class DownloadEntity extends DbEntity implements Parcelable, IEntity { public class DownloadEntity extends DbEntity implements Parcelable, IEntity {
@Ignore private long speed = 0; //下载速度 @Ignore private long speed = 0; //下载速度
@Ignore private String convertSpeed = "0b/s";
@Ignore private int failNum = 0; @Ignore private int failNum = 0;
private String downloadUrl = ""; //下载路径 private String downloadUrl = ""; //下载路径
private String downloadPath = ""; //保存路径 private String downloadPath = ""; //保存路径
@ -122,6 +123,14 @@ public class DownloadEntity extends DbEntity implements Parcelable, IEntity {
isDownloadComplete = downloadComplete; isDownloadComplete = downloadComplete;
} }
public String getConvertSpeed() {
return convertSpeed;
}
public void setConvertSpeed(String convertSpeed) {
this.convertSpeed = convertSpeed;
}
public long getSpeed() { public long getSpeed() {
return speed; return speed;
} }
@ -162,6 +171,9 @@ public class DownloadEntity extends DbEntity implements Parcelable, IEntity {
return "DownloadEntity{" return "DownloadEntity{"
+ "speed=" + "speed="
+ speed + speed
+ ", convertSpeed='"
+ convertSpeed
+ '\''
+ ", failNum=" + ", failNum="
+ failNum + failNum
+ ", downloadUrl='" + ", downloadUrl='"
@ -200,6 +212,7 @@ public class DownloadEntity extends DbEntity implements Parcelable, IEntity {
@Override public void writeToParcel(Parcel dest, int flags) { @Override public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.speed); dest.writeLong(this.speed);
dest.writeString(this.convertSpeed);
dest.writeInt(this.failNum); dest.writeInt(this.failNum);
dest.writeString(this.downloadUrl); dest.writeString(this.downloadUrl);
dest.writeString(this.downloadPath); dest.writeString(this.downloadPath);
@ -216,6 +229,7 @@ public class DownloadEntity extends DbEntity implements Parcelable, IEntity {
protected DownloadEntity(Parcel in) { protected DownloadEntity(Parcel in) {
this.speed = in.readLong(); this.speed = in.readLong();
this.convertSpeed = in.readString();
this.failNum = in.readInt(); this.failNum = in.readInt();
this.downloadUrl = in.readString(); this.downloadUrl = in.readString();
this.downloadPath = in.readString(); this.downloadPath = in.readString();

@ -23,10 +23,10 @@ final class DownloadStateConstance {
int CANCEL_NUM = 0; int CANCEL_NUM = 0;
int STOP_NUM = 0; int STOP_NUM = 0;
int FAIL_NUM = 0; int FAIL_NUM = 0;
int CONNECT_TIME_OUT = 5000 * 4; //连接超时时间 int CONNECT_TIME_OUT; //连接超时时间
int READ_TIME_OUT = 1000 * 20; //流读取的超时时间 int READ_TIME_OUT; //流读取的超时时间
int COMPLETE_THREAD_NUM = 0; int COMPLETE_THREAD_NUM = 0;
int THREAD_NUM = 3; int THREAD_NUM;
long CURRENT_LOCATION = 0; long CURRENT_LOCATION = 0;
boolean isDownloading = false; boolean isDownloading = false;
boolean isCancel = false; boolean isCancel = false;

@ -27,7 +27,6 @@ import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.ISchedulers; import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration_1;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
/** /**
@ -41,32 +40,61 @@ public class DownloadTask implements ITask {
*/ */
private String mTargetName; private String mTargetName;
private DownloadEntity mEntity; private DownloadEntity mEntity;
private DownloadTaskEntity mTaskEntity;
private IDownloadListener mListener; private IDownloadListener mListener;
private Handler mOutHandler; private Handler mOutHandler;
private IDownloadUtil mUtil; private IDownloadUtil mUtil;
private Context mContext; private Context mContext;
private DownloadTask(DownloadTaskEntity taskEntity, Handler outHandler) { private DownloadTask(DownloadTaskEntity taskEntity, Handler outHandler) {
mTaskEntity = taskEntity;
mEntity = taskEntity.downloadEntity; mEntity = taskEntity.downloadEntity;
mOutHandler = outHandler; mOutHandler = outHandler;
mContext = AriaManager.APP; mContext = AriaManager.APP;
init();
}
private void init() {
mListener = new DListener(mContext, this, mOutHandler); mListener = new DListener(mContext, this, mOutHandler);
mUtil = new DownloadUtil(mContext, mTaskEntity, mListener); mUtil = new DownloadUtil(mContext, taskEntity, mListener);
} }
/** /**
* 获取下载速度 * @return 返回原始byte速度需要你在配置文件中配置
* <pre>
* {@code
* <xml>
* <download>
* ...
* <convertSpeed value="false"/>
* </download>
*
* 或在代码中设置
* Aria.get(this).getDownloadConfig().setConvertSpeed(false);
* </xml>
* }
* </pre>
* 才能生效
*/ */
@Override public long getSpeed() { @Override public long getSpeed() {
return mEntity.getSpeed(); return mEntity.getSpeed();
} }
/**
* @return 返回转换单位后的速度需要你在配置文件中配置转换完成后为1b/s1k/s1m/s1g/s1t/s
* <pre>
* {@code
* <xml>
* <download>
* ...
* <convertSpeed value="true"/>
* </download>
*
* 或在代码中设置
* Aria.get(this).getDownloadConfig().setConvertSpeed(true);
* </xml>
* }
* </pre>
* 才能生效
*/
@Override public String getConvertSpeed() {
return mEntity.getConvertSpeed();
}
/** /**
* 获取文件大小 * 获取文件大小
*/ */
@ -178,32 +206,14 @@ public class DownloadTask implements ITask {
intent.putExtra(Aria.ENTITY, mEntity); intent.putExtra(Aria.ENTITY, mEntity);
mContext.sendBroadcast(intent); mContext.sendBroadcast(intent);
} }
//if (mEntity.isDownloadComplete()) {
// //mUtil.cancelDownload();
//} else {
// // 如果任务不是下载状态
// mUtil.cancelDownload();
// mUtil.delConfigFile();
// mUtil.delTempFile();
// mEntity.deleteData();
// if (mOutHandler != null) {
// mOutHandler.obtainMessage(DownloadSchedulers.CANCEL, this).sendToTarget();
// }
// //发送取消下载的广播
// Intent intent = CommonUtil.createIntent(mContext.getPackageName(), Aria.ACTION_CANCEL);
// intent.putExtra(Aria.ENTITY, mEntity);
// mContext.sendBroadcast(intent);
//}
} }
public static class Builder { public static class Builder {
DownloadTaskEntity taskEntity; DownloadTaskEntity taskEntity;
Handler outHandler; Handler outHandler;
int threadNum = 3;
String targetName; String targetName;
public Builder(String targetName, DownloadTaskEntity taskEntity) { public Builder(String targetName, DownloadTaskEntity taskEntity) {
//CheckUtil.checkDownloadTaskEntity(taskEntity.downloadEntity);
CheckUtil.checkTaskEntity(taskEntity); CheckUtil.checkTaskEntity(taskEntity);
this.targetName = targetName; this.targetName = targetName;
this.taskEntity = taskEntity; this.taskEntity = taskEntity;
@ -219,14 +229,6 @@ public class DownloadTask implements ITask {
return this; return this;
} }
/**
* 设置线程数
*/
public Builder setThreadNum(int threadNum) {
this.threadNum = threadNum;
return this;
}
public DownloadTask build() { public DownloadTask build() {
DownloadTask task = new DownloadTask(taskEntity, outHandler); DownloadTask task = new DownloadTask(taskEntity, outHandler);
task.setTargetName(targetName); task.setTargetName(targetName);
@ -243,13 +245,14 @@ public class DownloadTask implements ITask {
WeakReference<DownloadTask> wTask; WeakReference<DownloadTask> wTask;
Context context; Context context;
Intent sendIntent; Intent sendIntent;
long INTERVAL = 1024 * 10; //10k大小的间隔
long lastLen = 0; //上一次发送长度 long lastLen = 0; //上一次发送长度
long lastTime = 0; long lastTime = 0;
long INTERVAL_TIME = 1000; //1m更新周期 long INTERVAL_TIME = 1000; //1m更新周期
boolean isFirst = true; boolean isFirst = true;
DownloadEntity downloadEntity; DownloadEntity downloadEntity;
DownloadTask task; DownloadTask task;
boolean isOpenBroadCast = false;
boolean isConvertSpeed = false;
DListener(Context context, DownloadTask task, Handler outHandler) { DListener(Context context, DownloadTask task, Handler outHandler) {
this.context = context; this.context = context;
@ -259,6 +262,9 @@ public class DownloadTask implements ITask {
this.downloadEntity = this.task.getDownloadEntity(); this.downloadEntity = this.task.getDownloadEntity();
sendIntent = CommonUtil.createIntent(context.getPackageName(), Aria.ACTION_RUNNING); sendIntent = CommonUtil.createIntent(context.getPackageName(), Aria.ACTION_RUNNING);
sendIntent.putExtra(Aria.ENTITY, downloadEntity); sendIntent.putExtra(Aria.ENTITY, downloadEntity);
final AriaManager manager = AriaManager.getInstance(context);
isOpenBroadCast = manager.getDownloadConfig().isOpenBreadCast();
isConvertSpeed = manager.getDownloadConfig().isConvertSpeed();
} }
@Override public void supportBreakpoint(boolean support) { @Override public void supportBreakpoint(boolean support) {
@ -305,11 +311,10 @@ public class DownloadTask implements ITask {
sendIntent.putExtra(Aria.CURRENT_SPEED, speed); sendIntent.putExtra(Aria.CURRENT_SPEED, speed);
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
if (isFirst) { if (isFirst) {
downloadEntity.setSpeed(0); speed = 0;
isFirst = false; isFirst = false;
} else {
downloadEntity.setSpeed(speed);
} }
handleSpeed(speed);
downloadEntity.setCurrentProgress(currentLocation); downloadEntity.setCurrentProgress(currentLocation);
lastLen = currentLocation; lastLen = currentLocation;
sendInState2Target(DownloadSchedulers.RUNNING); sendInState2Target(DownloadSchedulers.RUNNING);
@ -320,7 +325,7 @@ public class DownloadTask implements ITask {
@Override public void onStop(long stopLocation) { @Override public void onStop(long stopLocation) {
super.onStop(stopLocation); super.onStop(stopLocation);
downloadEntity.setState(DownloadEntity.STATE_STOP); downloadEntity.setState(DownloadEntity.STATE_STOP);
downloadEntity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.STOP); sendInState2Target(DownloadSchedulers.STOP);
sendIntent(Aria.ACTION_STOP, stopLocation); sendIntent(Aria.ACTION_STOP, stopLocation);
} }
@ -328,6 +333,7 @@ public class DownloadTask implements ITask {
@Override public void onCancel() { @Override public void onCancel() {
super.onCancel(); super.onCancel();
downloadEntity.setState(DownloadEntity.STATE_CANCEL); downloadEntity.setState(DownloadEntity.STATE_CANCEL);
handleSpeed(0);
sendInState2Target(DownloadSchedulers.CANCEL); sendInState2Target(DownloadSchedulers.CANCEL);
sendIntent(Aria.ACTION_CANCEL, -1); sendIntent(Aria.ACTION_CANCEL, -1);
downloadEntity.deleteData(); downloadEntity.deleteData();
@ -337,7 +343,7 @@ public class DownloadTask implements ITask {
super.onComplete(); super.onComplete();
downloadEntity.setState(DownloadEntity.STATE_COMPLETE); downloadEntity.setState(DownloadEntity.STATE_COMPLETE);
downloadEntity.setDownloadComplete(true); downloadEntity.setDownloadComplete(true);
downloadEntity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.COMPLETE); sendInState2Target(DownloadSchedulers.COMPLETE);
sendIntent(Aria.ACTION_COMPLETE, downloadEntity.getFileSize()); sendIntent(Aria.ACTION_COMPLETE, downloadEntity.getFileSize());
} }
@ -346,11 +352,19 @@ public class DownloadTask implements ITask {
super.onFail(); super.onFail();
downloadEntity.setFailNum(downloadEntity.getFailNum() + 1); downloadEntity.setFailNum(downloadEntity.getFailNum() + 1);
downloadEntity.setState(DownloadEntity.STATE_FAIL); downloadEntity.setState(DownloadEntity.STATE_FAIL);
downloadEntity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.FAIL); sendInState2Target(DownloadSchedulers.FAIL);
sendIntent(Aria.ACTION_FAIL, -1); sendIntent(Aria.ACTION_FAIL, -1);
} }
private void handleSpeed(long speed) {
if (isConvertSpeed) {
downloadEntity.setConvertSpeed(CommonUtil.formatFileSize(speed) + "/s");
} else {
downloadEntity.setSpeed(speed);
}
}
/** /**
* 将任务状态发送给下载器 * 将任务状态发送给下载器
* *
@ -366,7 +380,7 @@ public class DownloadTask implements ITask {
downloadEntity.setDownloadComplete(action.equals(Aria.ACTION_COMPLETE)); downloadEntity.setDownloadComplete(action.equals(Aria.ACTION_COMPLETE));
downloadEntity.setCurrentProgress(location); downloadEntity.setCurrentProgress(location);
downloadEntity.update(); downloadEntity.update();
if (!Configuration_1.isOpenBreadCast) return; if (!isOpenBroadCast) return;
Intent intent = CommonUtil.createIntent(context.getPackageName(), action); Intent intent = CommonUtil.createIntent(context.getPackageName(), action);
intent.putExtra(Aria.ENTITY, downloadEntity); intent.putExtra(Aria.ENTITY, downloadEntity);
if (location != -1) { if (location != -1) {

@ -19,6 +19,7 @@ package com.arialyy.aria.core.download;
import android.content.Context; import android.content.Context;
import android.util.Log; import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.util.BufferedRandomAccessFile; import com.arialyy.aria.util.BufferedRandomAccessFile;
import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
@ -34,7 +35,7 @@ import java.util.concurrent.Executors;
* Created by lyy on 2015/8/25. * Created by lyy on 2015/8/25.
* 下载工具类 * 下载工具类
*/ */
public class DownloadUtil implements IDownloadUtil, Runnable { class DownloadUtil implements IDownloadUtil, Runnable {
private static final String TAG = "DownloadUtil"; private static final String TAG = "DownloadUtil";
/** /**
* 线程数 * 线程数
@ -46,8 +47,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
private static final long SUB_LEN = 1024 * 1024; private static final long SUB_LEN = 1024 * 1024;
//下载监听 //下载监听
private IDownloadListener mListener; private IDownloadListener mListener;
private int mConnectTimeOut = 5000 * 4; //连接超时时间 private int mConnectTimeOut = 0; //连接超时时间
private int mReadTimeOut = 5000 * 20; //流读取的超时时间
private boolean isNewTask = true; private boolean isNewTask = true;
private boolean isSupportBreakpoint = true; private boolean isSupportBreakpoint = true;
private Context mContext; private Context mContext;
@ -57,34 +57,29 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
private File mDownloadFile; //下载的文件 private File mDownloadFile; //下载的文件
private File mConfigFile;//下载信息配置文件 private File mConfigFile;//下载信息配置文件
private SparseArray<Runnable> mTask = new SparseArray<>(); private SparseArray<Runnable> mTask = new SparseArray<>();
private DownloadStateConstance mConstance; private DownloadStateConstance CONSTANCE;
DownloadUtil(Context context, DownloadTaskEntity entity, IDownloadListener downloadListener) { DownloadUtil(Context context, DownloadTaskEntity entity, IDownloadListener downloadListener) {
this(context, entity, downloadListener, 3);
}
DownloadUtil(Context context, DownloadTaskEntity entity, IDownloadListener downloadListener,
int threadNum) {
//CheckUtil.checkDownloadTaskEntity(entity.downloadEntity);
CheckUtil.checkTaskEntity(entity); CheckUtil.checkTaskEntity(entity);
mDownloadEntity = entity.downloadEntity; mDownloadEntity = entity.downloadEntity;
mContext = context.getApplicationContext(); mContext = context.getApplicationContext();
mDownloadTaskEntity = entity; mDownloadTaskEntity = entity;
mListener = downloadListener; mListener = downloadListener;
THREAD_NUM = threadNum; // 线程下载数改变后,新的下载才会生效
mFixedThreadPool = Executors.newFixedThreadPool(Integer.MAX_VALUE); mFixedThreadPool = Executors.newFixedThreadPool(Integer.MAX_VALUE);
mConstance = new DownloadStateConstance(); CONSTANCE = new DownloadStateConstance();
init(); init();
} }
private void init() { private void init() {
mConnectTimeOut = AriaManager.getInstance(mContext).getDownloadConfig().getConnectTimeOut();
mDownloadFile = new File(mDownloadTaskEntity.downloadEntity.getDownloadPath()); mDownloadFile = new File(mDownloadTaskEntity.downloadEntity.getDownloadPath());
//读取已完成的线程数 //读取已完成的线程数
mConfigFile = new File( mConfigFile = new File(
mContext.getFilesDir().getPath() + "/temp/" + mDownloadFile.getName() + ".properties"); mContext.getFilesDir().getPath() + "/temp/" + mDownloadFile.getName() + ".properties");
try { try {
if (!mConfigFile.exists()) { //记录文件被删除,则重新下载 if (!mConfigFile.exists()) { //记录文件被删除,则重新下载
isNewTask = true; handleNewTask();
CommonUtil.createFile(mConfigFile.getPath()); CommonUtil.createFile(mConfigFile.getPath());
} else { } else {
isNewTask = !mDownloadFile.exists(); isNewTask = !mDownloadFile.exists();
@ -99,37 +94,23 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
return mListener; return mListener;
} }
/**
* 设置连接超时时间
*/
public void setConnectTimeOut(int timeOut) {
mConnectTimeOut = timeOut;
}
/**
* 设置流读取的超时时间
*/
public void setReadTimeOut(int readTimeOut) {
mReadTimeOut = readTimeOut;
}
/** /**
* 获取当前下载位置 * 获取当前下载位置
*/ */
@Override public long getCurrentLocation() { @Override public long getCurrentLocation() {
return mConstance.CURRENT_LOCATION; return CONSTANCE.CURRENT_LOCATION;
} }
@Override public boolean isDownloading() { @Override public boolean isDownloading() {
return mConstance.isDownloading; return CONSTANCE.isDownloading;
} }
/** /**
* 取消下载 * 取消下载
*/ */
@Override public void cancelDownload() { @Override public void cancelDownload() {
mConstance.isCancel = true; CONSTANCE.isCancel = true;
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mFixedThreadPool.shutdown(); mFixedThreadPool.shutdown();
for (int i = 0; i < THREAD_NUM; i++) { for (int i = 0; i < THREAD_NUM; i++) {
SingleThreadTask task = (SingleThreadTask) mTask.get(i); SingleThreadTask task = (SingleThreadTask) mTask.get(i);
@ -143,8 +124,8 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
* 停止下载 * 停止下载
*/ */
@Override public void stopDownload() { @Override public void stopDownload() {
mConstance.isStop = true; CONSTANCE.isStop = true;
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mFixedThreadPool.shutdown(); mFixedThreadPool.shutdown();
for (int i = 0; i < THREAD_NUM; i++) { for (int i = 0; i < THREAD_NUM; i++) {
SingleThreadTask task = (SingleThreadTask) mTask.get(i); SingleThreadTask task = (SingleThreadTask) mTask.get(i);
@ -184,7 +165,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
* 多线程断点续传下载文件开始下载 * 多线程断点续传下载文件开始下载
*/ */
@Override public void startDownload() { @Override public void startDownload() {
mConstance.cleanState(); CONSTANCE.cleanState();
mListener.onPre(); mListener.onPre();
new Thread(this).start(); new Thread(this).start();
} }
@ -195,7 +176,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
private void failDownload(String msg) { private void failDownload(String msg) {
Log.e(TAG, msg); Log.e(TAG, msg);
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
stopDownload(); stopDownload();
mListener.onFail(); mListener.onFail();
} }
@ -206,7 +187,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
HttpURLConnection conn = ConnectionHelp.handleConnection(url); HttpURLConnection conn = ConnectionHelp.handleConnection(url);
conn = ConnectionHelp.setConnectParam(mDownloadTaskEntity, conn); conn = ConnectionHelp.setConnectParam(mDownloadTaskEntity, conn);
conn.setRequestProperty("Range", "bytes=" + 0 + "-"); conn.setRequestProperty("Range", "bytes=" + 0 + "-");
conn.setConnectTimeout(mConnectTimeOut * 4); conn.setConnectTimeout(mConnectTimeOut);
conn.connect(); conn.connect();
handleConnect(conn); handleConnect(conn);
} catch (IOException e) { } catch (IOException e) {
@ -283,7 +264,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
conn = ConnectionHelp.setConnectParam(mDownloadTaskEntity, conn); conn = ConnectionHelp.setConnectParam(mDownloadTaskEntity, conn);
conn.setRequestProperty("Cookie", cookies); conn.setRequestProperty("Cookie", cookies);
conn.setRequestProperty("Range", "bytes=" + 0 + "-"); conn.setRequestProperty("Range", "bytes=" + 0 + "-");
conn.setConnectTimeout(mConnectTimeOut * 4); conn.setConnectTimeout(mConnectTimeOut);
conn.connect(); conn.connect();
handleConnect(conn); handleConnect(conn);
@ -301,7 +282,7 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
int fileLength = conn.getContentLength(); int fileLength = conn.getContentLength();
if (fileLength < SUB_LEN) { if (fileLength < SUB_LEN) {
THREAD_NUM = 1; THREAD_NUM = 1;
mConstance.THREAD_NUM = THREAD_NUM; CONSTANCE.THREAD_NUM = THREAD_NUM;
} }
Properties pro = createConfigFile(fileLength); Properties pro = createConfigFile(fileLength);
int blockSize = fileLength / THREAD_NUM; int blockSize = fileLength / THREAD_NUM;
@ -322,14 +303,14 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
//如果有记录,则恢复下载 //如果有记录,则恢复下载
if (!isNewTask && record != null && Long.parseLong(record + "") > 0) { if (!isNewTask && record != null && Long.parseLong(record + "") > 0) {
Long r = Long.parseLong(record + ""); Long r = Long.parseLong(record + "");
mConstance.CURRENT_LOCATION += r - startL; CONSTANCE.CURRENT_LOCATION += r - startL;
Log.d(TAG, "++++++++++ 线程_" + i + "_恢复下载 ++++++++++"); Log.d(TAG, "++++++++++ 线程_" + i + "_恢复下载 ++++++++++");
mListener.onChildResume(r); mListener.onChildResume(r);
startL = r; startL = r;
recordL[rl] = i; recordL[rl] = i;
rl++; rl++;
} else { } else {
isNewTask = true; handleNewTask();
} }
if (isNewTask) { if (isNewTask) {
recordL[rl] = i; recordL[rl] = i;
@ -351,7 +332,6 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
ConfigEntity entity = new ConfigEntity(); ConfigEntity entity = new ConfigEntity();
long len = conn.getContentLength(); long len = conn.getContentLength();
entity.FILE_SIZE = len; entity.FILE_SIZE = len;
//entity.DOWNLOAD_URL = mDownloadEntity.getDownloadUrl();
entity.DOWNLOAD_URL = mDownloadEntity.isRedirect() ? mDownloadEntity.getRedirectUrl() entity.DOWNLOAD_URL = mDownloadEntity.isRedirect() ? mDownloadEntity.getRedirectUrl()
: mDownloadEntity.getDownloadUrl(); : mDownloadEntity.getDownloadUrl();
entity.TEMP_FILE = mDownloadFile; entity.TEMP_FILE = mDownloadFile;
@ -362,8 +342,8 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
entity.isSupportBreakpoint = isSupportBreakpoint; entity.isSupportBreakpoint = isSupportBreakpoint;
entity.DOWNLOAD_TASK_ENTITY = mDownloadTaskEntity; entity.DOWNLOAD_TASK_ENTITY = mDownloadTaskEntity;
THREAD_NUM = 1; THREAD_NUM = 1;
mConstance.THREAD_NUM = THREAD_NUM; CONSTANCE.THREAD_NUM = THREAD_NUM;
SingleThreadTask task = new SingleThreadTask(mConstance, mListener, entity); SingleThreadTask task = new SingleThreadTask(CONSTANCE, mListener, entity);
mTask.put(0, task); mTask.put(0, task);
mFixedThreadPool.execute(task); mFixedThreadPool.execute(task);
mListener.onPostPre(len); mListener.onPostPre(len);
@ -385,15 +365,16 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
//分配每条线程的下载区间 //分配每条线程的下载区间
pro = CommonUtil.loadConfig(mConfigFile); pro = CommonUtil.loadConfig(mConfigFile);
if (pro.isEmpty()) { if (pro.isEmpty()) {
isNewTask = true; handleNewTask();
} else { } else {
THREAD_NUM = pro.keySet().size();
for (int i = 0; i < THREAD_NUM; i++) { for (int i = 0; i < THREAD_NUM; i++) {
if (pro.getProperty(mDownloadFile.getName() + "_record_" + i) == null) { if (pro.getProperty(mDownloadFile.getName() + "_record_" + i) == null) {
Object state = pro.getProperty(mDownloadFile.getName() + "_state_" + i); Object state = pro.getProperty(mDownloadFile.getName() + "_state_" + i);
if (state != null && Integer.parseInt(state + "") == 1) { if (state != null && Integer.parseInt(state + "") == 1) {
continue; continue;
} }
isNewTask = true; handleNewTask();
break; break;
} }
} }
@ -401,23 +382,31 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
return pro; return pro;
} }
/**
* 处理新任务
*/
private void handleNewTask() {
isNewTask = true;
THREAD_NUM = AriaManager.getInstance(mContext).getDownloadConfig().getThreadNum();
}
/** /**
* 恢复记录地址 * 恢复记录地址
* *
* @return true 表示下载完成 * @return true 表示下载完成
*/ */
private boolean resumeRecordLocation(int i, long startL, long endL) { private boolean resumeRecordLocation(int i, long startL, long endL) {
mConstance.CURRENT_LOCATION += endL - startL; CONSTANCE.CURRENT_LOCATION += endL - startL;
Log.d(TAG, "++++++++++ 线程_" + i + "_已经下载完成 ++++++++++"); Log.d(TAG, "++++++++++ 线程_" + i + "_已经下载完成 ++++++++++");
mConstance.COMPLETE_THREAD_NUM++; CONSTANCE.COMPLETE_THREAD_NUM++;
mConstance.STOP_NUM++; CONSTANCE.STOP_NUM++;
mConstance.CANCEL_NUM++; CONSTANCE.CANCEL_NUM++;
if (mConstance.isComplete()) { if (CONSTANCE.isComplete()) {
if (mConfigFile.exists()) { if (mConfigFile.exists()) {
mConfigFile.delete(); mConfigFile.delete();
} }
mListener.onComplete(); mListener.onComplete();
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
return true; return true;
} }
return false; return false;
@ -439,7 +428,8 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
entity.CONFIG_FILE_PATH = mConfigFile.getPath(); entity.CONFIG_FILE_PATH = mConfigFile.getPath();
entity.isSupportBreakpoint = isSupportBreakpoint; entity.isSupportBreakpoint = isSupportBreakpoint;
entity.DOWNLOAD_TASK_ENTITY = mDownloadTaskEntity; entity.DOWNLOAD_TASK_ENTITY = mDownloadTaskEntity;
SingleThreadTask task = new SingleThreadTask(mConstance, mListener, entity); CONSTANCE.THREAD_NUM = THREAD_NUM;
SingleThreadTask task = new SingleThreadTask(CONSTANCE, mListener, entity);
mTask.put(i, task); mTask.put(i, task);
} }
@ -447,10 +437,10 @@ public class DownloadUtil implements IDownloadUtil, Runnable {
* 启动单线程下载任务 * 启动单线程下载任务
*/ */
private void startSingleTask(int[] recordL) { private void startSingleTask(int[] recordL) {
if (mConstance.CURRENT_LOCATION > 0) { if (CONSTANCE.CURRENT_LOCATION > 0) {
mListener.onResume(mConstance.CURRENT_LOCATION); mListener.onResume(CONSTANCE.CURRENT_LOCATION);
} else { } else {
mListener.onStart(mConstance.CURRENT_LOCATION); mListener.onStart(CONSTANCE.CURRENT_LOCATION);
} }
for (int l : recordL) { for (int l : recordL) {
if (l == -1) continue; if (l == -1) continue;

@ -15,10 +15,8 @@
*/ */
package com.arialyy.aria.core.download; package com.arialyy.aria.core.download;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.util.BufferedRandomAccessFile; import com.arialyy.aria.util.BufferedRandomAccessFile;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import java.io.File; import java.io.File;
@ -34,35 +32,34 @@ import java.util.Properties;
* 下载线程 * 下载线程
*/ */
final class SingleThreadTask implements Runnable { final class SingleThreadTask implements Runnable {
private static final String TAG = "SingleThreadTask"; private static final String TAG = "SingleThreadTask";
// TODO: 2017/2/22 不能使用1024 否则最大速度不能超过3m
private static final int BUF_SIZE = 8192;
private DownloadUtil.ConfigEntity mConfigEntity; private DownloadUtil.ConfigEntity mConfigEntity;
private String mConfigFPath; private String mConfigFPath;
private long mChildCurrentLocation = 0; private long mChildCurrentLocation = 0;
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private int mBufSize = 8192; private int mBufSize;
//private int mBufSize = 64;
private IDownloadListener mListener; private IDownloadListener mListener;
private DownloadStateConstance mConstance; private DownloadStateConstance CONSTANCE;
SingleThreadTask(DownloadStateConstance constance, IDownloadListener listener, SingleThreadTask(DownloadStateConstance constance, IDownloadListener listener,
DownloadUtil.ConfigEntity downloadInfo) { DownloadUtil.ConfigEntity downloadInfo) {
mConstance = constance; AriaManager manager = AriaManager.getInstance(AriaManager.APP);
CONSTANCE = constance;
CONSTANCE.CONNECT_TIME_OUT = manager.getDownloadConfig().getConnectTimeOut();
CONSTANCE.READ_TIME_OUT = manager.getDownloadConfig().getIOTimeOut();
mListener = listener; mListener = listener;
this.mConfigEntity = downloadInfo; this.mConfigEntity = downloadInfo;
if (mConfigEntity.isSupportBreakpoint) { if (mConfigEntity.isSupportBreakpoint) {
mConfigFPath = downloadInfo.CONFIG_FILE_PATH; mConfigFPath = downloadInfo.CONFIG_FILE_PATH;
} }
//mBufSize = Configuration_1.getInstance().getMaxSpeed(); mBufSize = manager.getDownloadConfig().getBuffSize();
} }
@Override public void run() { @Override public void run() {
HttpURLConnection conn = null; HttpURLConnection conn;
InputStream is = null; InputStream is;
try { try {
URL url = new URL(mConfigEntity.DOWNLOAD_URL); URL url = new URL(mConfigEntity.DOWNLOAD_URL);
//conn = (HttpURLConnection) url.openConnection();
conn = ConnectionHelp.handleConnection(url); conn = ConnectionHelp.handleConnection(url);
if (mConfigEntity.isSupportBreakpoint) { if (mConfigEntity.isSupportBreakpoint) {
Log.d(TAG, "线程_" Log.d(TAG, "线程_"
@ -79,8 +76,8 @@ final class SingleThreadTask implements Runnable {
Log.w(TAG, "该下载不支持断点"); Log.w(TAG, "该下载不支持断点");
} }
conn = ConnectionHelp.setConnectParam(mConfigEntity.DOWNLOAD_TASK_ENTITY, conn); conn = ConnectionHelp.setConnectParam(mConfigEntity.DOWNLOAD_TASK_ENTITY, conn);
conn.setConnectTimeout(mConstance.CONNECT_TIME_OUT); conn.setConnectTimeout(CONSTANCE.CONNECT_TIME_OUT);
conn.setReadTimeout(mConstance.READ_TIME_OUT); //设置读取流的等待时间,必须设置该参数 conn.setReadTimeout(CONSTANCE.READ_TIME_OUT); //设置读取流的等待时间,必须设置该参数
is = conn.getInputStream(); is = conn.getInputStream();
//创建可设置位置的文件 //创建可设置位置的文件
BufferedRandomAccessFile file = BufferedRandomAccessFile file =
@ -92,10 +89,10 @@ final class SingleThreadTask implements Runnable {
//当前子线程的下载位置 //当前子线程的下载位置
mChildCurrentLocation = mConfigEntity.START_LOCATION; mChildCurrentLocation = mConfigEntity.START_LOCATION;
while ((len = is.read(buffer)) != -1) { while ((len = is.read(buffer)) != -1) {
if (mConstance.isCancel) { if (CONSTANCE.isCancel) {
break; break;
} }
if (mConstance.isStop) { if (CONSTANCE.isStop) {
break; break;
} }
//把下载数据数据写入文件 //把下载数据数据写入文件
@ -106,11 +103,11 @@ final class SingleThreadTask implements Runnable {
//close 为阻塞的,需要使用线程池来处理 //close 为阻塞的,需要使用线程池来处理
is.close(); is.close();
conn.disconnect(); conn.disconnect();
if (mConstance.isCancel) { if (CONSTANCE.isCancel) {
return; return;
} }
//停止状态不需要删除记录文件 //停止状态不需要删除记录文件
if (mConstance.isStop) { if (CONSTANCE.isStop) {
return; return;
} }
//支持断点的处理 //支持断点的处理
@ -119,29 +116,29 @@ final class SingleThreadTask implements Runnable {
writeConfig(mConfigEntity.TEMP_FILE.getName() + "_state_" + mConfigEntity.THREAD_ID, writeConfig(mConfigEntity.TEMP_FILE.getName() + "_state_" + mConfigEntity.THREAD_ID,
1 + ""); 1 + "");
mListener.onChildComplete(mConfigEntity.END_LOCATION); mListener.onChildComplete(mConfigEntity.END_LOCATION);
mConstance.COMPLETE_THREAD_NUM++; CONSTANCE.COMPLETE_THREAD_NUM++;
if (mConstance.isComplete()) { if (CONSTANCE.isComplete()) {
File configFile = new File(mConfigFPath); File configFile = new File(mConfigFPath);
if (configFile.exists()) { if (configFile.exists()) {
configFile.delete(); configFile.delete();
} }
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onComplete(); mListener.onComplete();
} }
} else { } else {
Log.i(TAG, "下载任务完成"); Log.i(TAG, "下载任务完成");
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onComplete(); mListener.onComplete();
} }
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
mConstance.FAIL_NUM++; CONSTANCE.FAIL_NUM++;
failDownload(mConfigEntity, mChildCurrentLocation, "下载链接异常", e); failDownload(mConfigEntity, mChildCurrentLocation, "下载链接异常", e);
} catch (IOException e) { } catch (IOException e) {
mConstance.FAIL_NUM++; CONSTANCE.FAIL_NUM++;
failDownload(mConfigEntity, mChildCurrentLocation, "下载失败【" + mConfigEntity.DOWNLOAD_URL + "】", failDownload(mConfigEntity, mChildCurrentLocation, "下载失败【" + mConfigEntity.DOWNLOAD_URL + "】",
e); e);
} catch (Exception e) { } catch (Exception e) {
mConstance.FAIL_NUM++; CONSTANCE.FAIL_NUM++;
failDownload(mConfigEntity, mChildCurrentLocation, "获取流失败", e); failDownload(mConfigEntity, mChildCurrentLocation, "获取流失败", e);
} }
} }
@ -153,7 +150,7 @@ final class SingleThreadTask implements Runnable {
synchronized (LOCK) { synchronized (LOCK) {
try { try {
if (mConfigEntity.isSupportBreakpoint) { if (mConfigEntity.isSupportBreakpoint) {
mConstance.STOP_NUM++; CONSTANCE.STOP_NUM++;
String location = String.valueOf(mChildCurrentLocation); String location = String.valueOf(mChildCurrentLocation);
Log.d(TAG, "thread_" Log.d(TAG, "thread_"
+ mConfigEntity.THREAD_ID + mConfigEntity.THREAD_ID
@ -161,15 +158,15 @@ final class SingleThreadTask implements Runnable {
+ mChildCurrentLocation); + mChildCurrentLocation);
writeConfig(mConfigEntity.TEMP_FILE.getName() + "_record_" + mConfigEntity.THREAD_ID, writeConfig(mConfigEntity.TEMP_FILE.getName() + "_record_" + mConfigEntity.THREAD_ID,
location); location);
if (mConstance.isStop()) { if (CONSTANCE.isStop()) {
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onStop(mConstance.CURRENT_LOCATION); mListener.onStop(CONSTANCE.CURRENT_LOCATION);
} }
} else { } else {
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onStop(mConstance.CURRENT_LOCATION); mListener.onStop(CONSTANCE.CURRENT_LOCATION);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -183,44 +180,20 @@ final class SingleThreadTask implements Runnable {
private void progress(long len) { private void progress(long len) {
synchronized (LOCK) { synchronized (LOCK) {
mChildCurrentLocation += len; mChildCurrentLocation += len;
mConstance.CURRENT_LOCATION += len; CONSTANCE.CURRENT_LOCATION += len;
mListener.onProgress(mConstance.CURRENT_LOCATION); mListener.onProgress(CONSTANCE.CURRENT_LOCATION);
//mHandler.sendEmptyMessage(1);
//mHandler.post(t);
} }
} }
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
super.handleMessage(msg);
mListener.onProgress(mConstance.CURRENT_LOCATION);
}
};
Thread t = new Thread(new Runnable() {
@Override public void run() {
mListener.onProgress(mConstance.CURRENT_LOCATION);
}
});
//Handler handler = new Handler(){
// @Override public void handleMessage(Message msg) {
// super.handleMessage(msg);
// mListener.onProgress(mConstance.CURRENT_LOCATION);
// }
//};
Thread thread = new Thread();
/** /**
* 取消下载 * 取消下载
*/ */
protected void cancel() { protected void cancel() {
synchronized (LOCK) { synchronized (LOCK) {
if (mConfigEntity.isSupportBreakpoint) { if (mConfigEntity.isSupportBreakpoint) {
mConstance.CANCEL_NUM++; CONSTANCE.CANCEL_NUM++;
Log.d(TAG, "++++++++++ thread_" + mConfigEntity.THREAD_ID + "_cancel ++++++++++"); Log.d(TAG, "++++++++++ thread_" + mConfigEntity.THREAD_ID + "_cancel ++++++++++");
if (mConstance.isCancel()) { if (CONSTANCE.isCancel()) {
File configFile = new File(mConfigFPath); File configFile = new File(mConfigFPath);
if (configFile.exists()) { if (configFile.exists()) {
configFile.delete(); configFile.delete();
@ -229,12 +202,12 @@ final class SingleThreadTask implements Runnable {
mConfigEntity.TEMP_FILE.delete(); mConfigEntity.TEMP_FILE.delete();
} }
Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++");
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onCancel(); mListener.onCancel();
} }
} else { } else {
Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++");
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mListener.onCancel(); mListener.onCancel();
} }
} }
@ -247,8 +220,8 @@ final class SingleThreadTask implements Runnable {
Exception ex) { Exception ex) {
synchronized (LOCK) { synchronized (LOCK) {
try { try {
mConstance.isDownloading = false; CONSTANCE.isDownloading = false;
mConstance.isStop = true; CONSTANCE.isStop = true;
if (ex != null) { if (ex != null) {
Log.e(TAG, CommonUtil.getPrintException(ex)); Log.e(TAG, CommonUtil.getPrintException(ex));
} }
@ -257,7 +230,7 @@ final class SingleThreadTask implements Runnable {
String location = String.valueOf(currentLocation); String location = String.valueOf(currentLocation);
writeConfig(dEntity.TEMP_FILE.getName() + "_record_" + dEntity.THREAD_ID, location); writeConfig(dEntity.TEMP_FILE.getName() + "_record_" + dEntity.THREAD_ID, location);
} }
if (mConstance.isFail()) { if (CONSTANCE.isFail()) {
Log.d(TAG, "++++++++++++++++ onFail +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onFail +++++++++++++++++");
mListener.onFail(); mListener.onFail();
} }

@ -44,8 +44,16 @@ public interface ITask {
public void cancel(); public void cancel();
/**
* 原始byte速度
*/
public long getSpeed(); public long getSpeed();
/**
* 转换单位后的速度
*/
public String getConvertSpeed();
public long getFileSize(); public long getFileSize();
public long getCurrentProgress(); public long getCurrentProgress();

@ -28,5 +28,4 @@ import com.arialyy.aria.core.queue.pool.ExecutePool;
abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity, ENTITY extends IEntity> abstract class AbsTaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity, ENTITY extends IEntity>
implements ITaskQueue<TASK, TASK_ENTITY, ENTITY> { implements ITaskQueue<TASK, TASK_ENTITY, ENTITY> {
CachePool<TASK> mCachePool = new CachePool<>(); CachePool<TASK> mCachePool = new CachePool<>();
ExecutePool<TASK> mExecutePool = new ExecutePool<>();
} }

@ -18,6 +18,7 @@ package com.arialyy.aria.core.queue;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.download.DownloadTaskEntity; import com.arialyy.aria.core.download.DownloadTaskEntity;
@ -25,7 +26,6 @@ import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.queue.pool.CachePool; import com.arialyy.aria.core.queue.pool.CachePool;
import com.arialyy.aria.core.queue.pool.ExecutePool; import com.arialyy.aria.core.queue.pool.ExecutePool;
import com.arialyy.aria.core.scheduler.DownloadSchedulers; import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.util.Configuration_1;
/** /**
* Created by lyy on 2016/8/17. * Created by lyy on 2016/8/17.
@ -36,6 +36,7 @@ public class DownloadTaskQueue
private static final String TAG = "DownloadTaskQueue"; private static final String TAG = "DownloadTaskQueue";
private static volatile DownloadTaskQueue INSTANCE = null; private static volatile DownloadTaskQueue INSTANCE = null;
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private ExecutePool<DownloadTask> mExecutePool = new ExecutePool<>(true);
public static DownloadTaskQueue getInstance() { public static DownloadTaskQueue getInstance() {
if (INSTANCE == null) { if (INSTANCE == null) {
@ -121,7 +122,7 @@ public class DownloadTaskQueue
@Override public void setDownloadNum(int downloadNum) { @Override public void setDownloadNum(int downloadNum) {
//原始长度 //原始长度
int size = Configuration_1.getInstance().getDownloadNum(); int size = AriaManager.getInstance(AriaManager.APP).getDownloadConfig().oldMaxTaskNum;
int diff = downloadNum - size; int diff = downloadNum - size;
if (size == downloadNum) { if (size == downloadNum) {
Log.d(TAG, "设置的下载任务数和配置文件的下载任务数一直,跳过"); Log.d(TAG, "设置的下载任务数和配置文件的下载任务数一直,跳过");

@ -66,11 +66,11 @@ public interface ITaskQueue<TASK extends ITask, TASK_ENTITY extends ITaskEntity,
public int size(); public int size();
/** /**
* 设置下载任务数 * 设置最大任务数
* *
* @param downloadNum 下载任务数 * @param newMaxNum 下载任务数
*/ */
public void setDownloadNum(int downloadNum); public void setDownloadNum(int newMaxNum);
/** /**
* 创建一个新的任务创建时只是将新任务存储到缓存池 * 创建一个新的任务创建时只是将新任务存储到缓存池

@ -18,6 +18,8 @@ package com.arialyy.aria.core.queue;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.queue.pool.ExecutePool;
import com.arialyy.aria.core.scheduler.UploadSchedulers; import com.arialyy.aria.core.scheduler.UploadSchedulers;
import com.arialyy.aria.core.upload.UploadEntity; import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTask; import com.arialyy.aria.core.upload.UploadTask;
@ -31,6 +33,7 @@ public class UploadTaskQueue extends AbsTaskQueue<UploadTask, UploadTaskEntity,
private static final String TAG = "UploadTaskQueue"; private static final String TAG = "UploadTaskQueue";
private static volatile UploadTaskQueue INSTANCE = null; private static volatile UploadTaskQueue INSTANCE = null;
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private ExecutePool<UploadTask> mExecutePool = new ExecutePool<>(false);
public static UploadTaskQueue getInstance() { public static UploadTaskQueue getInstance() {
if (INSTANCE == null) { if (INSTANCE == null) {

@ -18,9 +18,9 @@ package com.arialyy.aria.core.queue.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.ITask; import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration_1;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
@ -38,8 +38,12 @@ public class ExecutePool<TASK extends ITask> implements IPool<TASK> {
private Map<String, TASK> mExecuteArray; private Map<String, TASK> mExecuteArray;
private int mSize; private int mSize;
public ExecutePool() { public ExecutePool(boolean isDownload) {
mSize = Configuration_1.getInstance().getDownloadNum(); if (isDownload) {
mSize = AriaManager.getInstance(AriaManager.APP).getDownloadConfig().getMaxTaskNum();
} else {
mSize = AriaManager.getInstance(AriaManager.APP).getUploadConfig().getMaxTaskNum();
}
mExecuteQueue = new ArrayBlockingQueue<>(mSize); mExecuteQueue = new ArrayBlockingQueue<>(mSize);
mExecuteArray = new HashMap<>(); mExecuteArray = new HashMap<>();
} }
@ -81,7 +85,6 @@ public class ExecutePool<TASK extends ITask> implements IPool<TASK> {
} }
mExecuteQueue = temp; mExecuteQueue = temp;
mSize = downloadNum; mSize = downloadNum;
Configuration_1.getInstance().setDownloadNum(mSize);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }

@ -19,10 +19,10 @@ package com.arialyy.aria.core.scheduler;
import android.os.CountDownTimer; import android.os.CountDownTimer;
import android.os.Message; import android.os.Message;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.queue.DownloadTaskQueue; import com.arialyy.aria.core.queue.DownloadTaskQueue;
import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTask; import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.util.Configuration_1;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -86,7 +86,9 @@ public class DownloadSchedulers implements ISchedulers<DownloadTask> {
case STOP: case STOP:
case CANCEL: case CANCEL:
mQueue.removeTask(entity); mQueue.removeTask(entity);
if (mQueue.size() < Configuration_1.getInstance().getDownloadNum()) { if (mQueue.size() < AriaManager.getInstance(AriaManager.APP)
.getUploadConfig()
.getMaxTaskNum()) {
startNextTask(); startNextTask();
} }
break; break;
@ -163,19 +165,22 @@ public class DownloadSchedulers implements ISchedulers<DownloadTask> {
* @param task 下载任务 * @param task 下载任务
*/ */
private void handleFailTask(final DownloadTask task) { private void handleFailTask(final DownloadTask task) {
final Configuration_1 config = Configuration_1.getInstance(); final long interval =
CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) { AriaManager.getInstance(AriaManager.APP).getUploadConfig().getReTryInterval();
final int reTryNum = AriaManager.getInstance(AriaManager.APP).getUploadConfig().getReTryNum();
CountDownTimer timer = new CountDownTimer(interval, 1000) {
@Override public void onTick(long millisUntilFinished) { @Override public void onTick(long millisUntilFinished) {
} }
@Override public void onFinish() { @Override public void onFinish() {
DownloadEntity entity = task.getDownloadEntity(); DownloadEntity entity = task.getDownloadEntity();
if (entity.getFailNum() < config.getReTryNum()) { if (entity.getFailNum() < reTryNum) {
DownloadTask task = mQueue.getTask(entity); DownloadTask task = mQueue.getTask(entity);
mQueue.reTryStart(task); mQueue.reTryStart(task);
try { try {
Thread.sleep(config.getReTryInterval()); Thread.sleep(interval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }

@ -18,11 +18,11 @@ package com.arialyy.aria.core.scheduler;
import android.os.CountDownTimer; import android.os.CountDownTimer;
import android.os.Message; import android.os.Message;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import com.arialyy.aria.core.inf.IEntity; import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.queue.UploadTaskQueue; import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.core.upload.UploadEntity; import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.aria.core.upload.UploadTask; import com.arialyy.aria.core.upload.UploadTask;
import com.arialyy.aria.util.Configuration_1;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -69,19 +69,21 @@ public class UploadSchedulers implements ISchedulers<UploadTask> {
} }
private void handleFailTask(final UploadTask task) { private void handleFailTask(final UploadTask task) {
final Configuration_1 config = Configuration_1.getInstance(); final long interval =
CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) { AriaManager.getInstance(AriaManager.APP).getUploadConfig().getReTryInterval();
final int reTryNum = AriaManager.getInstance(AriaManager.APP).getUploadConfig().getReTryNum();
CountDownTimer timer = new CountDownTimer(interval, 1000) {
@Override public void onTick(long millisUntilFinished) { @Override public void onTick(long millisUntilFinished) {
} }
@Override public void onFinish() { @Override public void onFinish() {
UploadEntity entity = task.getUploadEntity(); UploadEntity entity = task.getUploadEntity();
if (entity.getFailNum() <= config.getReTryNum()) { if (entity.getFailNum() <= reTryNum) {
UploadTask task = mQueue.getTask(entity); UploadTask task = mQueue.getTask(entity);
mQueue.reTryStart(task); mQueue.reTryStart(task);
try { try {
Thread.sleep(config.getReTryInterval()); Thread.sleep(interval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -169,7 +171,9 @@ public class UploadSchedulers implements ISchedulers<UploadTask> {
case STOP: case STOP:
case CANCEL: case CANCEL:
mQueue.removeTask(entity); mQueue.removeTask(entity);
if (mQueue.size() < Configuration_1.getInstance().getDownloadNum()) { if (mQueue.size() < AriaManager.getInstance(AriaManager.APP)
.getUploadConfig()
.getMaxTaskNum()) {
startNextTask(); startNextTask();
} }
break; break;

@ -34,8 +34,17 @@ public class UploadEntity extends DbEntity implements IEntity, Parcelable {
private long currentProgress = 0; private long currentProgress = 0;
private boolean isComplete = false; private boolean isComplete = false;
@Ignore private long speed = 0; //下载速度 @Ignore private long speed = 0; //下载速度
@Ignore private String convertSpeed = "0/s";
@Ignore private int failNum = 0; @Ignore private int failNum = 0;
public String getConvertSpeed() {
return convertSpeed;
}
public void setConvertSpeed(String convertSpeed) {
this.convertSpeed = convertSpeed;
}
public boolean isComplete() { public boolean isComplete() {
return isComplete; return isComplete;
} }
@ -115,6 +124,7 @@ public class UploadEntity extends DbEntity implements IEntity, Parcelable {
dest.writeLong(this.currentProgress); dest.writeLong(this.currentProgress);
dest.writeByte(this.isComplete ? (byte) 1 : (byte) 0); dest.writeByte(this.isComplete ? (byte) 1 : (byte) 0);
dest.writeLong(this.speed); dest.writeLong(this.speed);
dest.writeString(this.convertSpeed);
dest.writeInt(this.failNum); dest.writeInt(this.failNum);
} }
@ -126,6 +136,7 @@ public class UploadEntity extends DbEntity implements IEntity, Parcelable {
this.currentProgress = in.readLong(); this.currentProgress = in.readLong();
this.isComplete = in.readByte() != 0; this.isComplete = in.readByte() != 0;
this.speed = in.readLong(); this.speed = in.readLong();
this.convertSpeed = in.readString();
this.failNum = in.readInt(); this.failNum = in.readInt();
} }

@ -15,6 +15,7 @@
*/ */
package com.arialyy.aria.core.upload; package com.arialyy.aria.core.upload;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Handler; import android.os.Handler;
import android.util.Log; import android.util.Log;
@ -26,7 +27,6 @@ import com.arialyy.aria.core.inf.ITask;
import com.arialyy.aria.core.scheduler.DownloadSchedulers; import com.arialyy.aria.core.scheduler.DownloadSchedulers;
import com.arialyy.aria.core.scheduler.ISchedulers; import com.arialyy.aria.core.scheduler.ISchedulers;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.Configuration_1;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
/** /**
@ -36,19 +36,17 @@ import java.lang.ref.WeakReference;
public class UploadTask implements ITask { public class UploadTask implements ITask {
private static final String TAG = "UploadTask"; private static final String TAG = "UploadTask";
private Handler mOutHandler; private Handler mOutHandler;
private UploadTaskEntity mTaskEntity;
private UploadEntity mUploadEntity; private UploadEntity mUploadEntity;
private String mTargetName; private String mTargetName;
private UploadUtil mUtil; private UploadUtil mUtil;
private UListener mListener; private UListener mListener;
UploadTask(UploadTaskEntity taskEntity, Handler outHandler) { private UploadTask(UploadTaskEntity taskEntity, Handler outHandler) {
mTaskEntity = taskEntity;
mOutHandler = outHandler; mOutHandler = outHandler;
mUploadEntity = mTaskEntity.uploadEntity; mUploadEntity = taskEntity.uploadEntity;
mListener = new UListener(mOutHandler, this); mListener = new UListener(mOutHandler, this);
mUtil = new UploadUtil(mTaskEntity, mListener); mUtil = new UploadUtil(taskEntity, mListener);
} }
@Override public void setTargetName(String targetName) { @Override public void setTargetName(String targetName) {
@ -104,31 +102,55 @@ public class UploadTask implements ITask {
intent.putExtra(Aria.ENTITY, mUploadEntity); intent.putExtra(Aria.ENTITY, mUploadEntity);
AriaManager.APP.sendBroadcast(intent); AriaManager.APP.sendBroadcast(intent);
} }
//if (mUtil.isRunning()) {
// mUtil.cancel();
//} else {
// // 如果任务不是下载状态
// mUtil.cancel();
// mUploadEntity.deleteData();
// if (mOutHandler != null) {
// mOutHandler.obtainMessage(DownloadSchedulers.CANCEL, this).sendToTarget();
// }
// //发送取消下载的广播
// Intent intent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), Aria.ACTION_CANCEL);
// intent.putExtra(Aria.ENTITY, mUploadEntity);
// AriaManager.APP.sendBroadcast(intent);
//}
} }
public String getTargetName() { public String getTargetName() {
return mTargetName; return mTargetName;
} }
/**
* @return 返回原始byte速度需要你在配置文件中配置
* <pre>
* {@code
* <xml>
* <upload>
* ...
* <convertSpeed value="false"/>
* </upload>
*
* 或在代码中设置
* Aria.get(this).getUploadConfig().setConvertSpeed(false);
* </xml>
* }
* </pre>
* 才能生效
*/
@Override public long getSpeed() { @Override public long getSpeed() {
return mUploadEntity.getSpeed(); return mUploadEntity.getSpeed();
} }
/**
* @return 返回转换单位后的速度需要你在配置文件中配置转换完成后为1b/s1k/s1m/s1g/s1t/s
* <pre>
* {@code
* <xml>
* <upload>
* ...
* <convertSpeed value="true"/>
* </upload>
*
* 或在代码中设置
* Aria.get(this).getUploadConfig().setConvertSpeed(true);
* </xml>
* }
* </pre>
*
* 才能生效
*/
@Override public String getConvertSpeed() {
return mUploadEntity.getConvertSpeed();
}
@Override public long getFileSize() { @Override public long getFileSize() {
return mUploadEntity.getFileSize(); return mUploadEntity.getFileSize();
} }
@ -144,39 +166,46 @@ public class UploadTask implements ITask {
long lastTime = 0; long lastTime = 0;
long INTERVAL_TIME = 1000; //1m更新周期 long INTERVAL_TIME = 1000; //1m更新周期
boolean isFirst = true; boolean isFirst = true;
UploadEntity entity; UploadEntity uploadEntity;
Intent sendIntent; Intent sendIntent;
boolean isOpenBroadCast = false;
boolean isConvertSpeed = false;
Context context;
UListener(Handler outHandle, UploadTask task) { UListener(Handler outHandle, UploadTask task) {
this.outHandler = new WeakReference<>(outHandle); this.outHandler = new WeakReference<>(outHandle);
this.task = new WeakReference<>(task); this.task = new WeakReference<>(task);
entity = this.task.get().getUploadEntity(); uploadEntity = this.task.get().getUploadEntity();
sendIntent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), Aria.ACTION_RUNNING); sendIntent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), Aria.ACTION_RUNNING);
sendIntent.putExtra(Aria.ENTITY, entity); sendIntent.putExtra(Aria.ENTITY, uploadEntity);
context = AriaManager.APP;
final AriaManager manager = AriaManager.getInstance(context);
isOpenBroadCast = manager.getUploadConfig().isOpenBreadCast();
isConvertSpeed = manager.getUploadConfig().isConvertSpeed();
} }
@Override public void onPre() { @Override public void onPre() {
entity.setState(IEntity.STATE_PRE); uploadEntity.setState(IEntity.STATE_PRE);
sendIntent(Aria.ACTION_PRE, -1); sendIntent(Aria.ACTION_PRE, -1);
sendInState2Target(ISchedulers.PRE); sendInState2Target(ISchedulers.PRE);
} }
@Override public void onStart(long fileSize) { @Override public void onStart(long fileSize) {
entity.setFileSize(fileSize); uploadEntity.setFileSize(fileSize);
entity.setState(IEntity.STATE_RUNNING); uploadEntity.setState(IEntity.STATE_RUNNING);
sendIntent(Aria.ACTION_PRE, -1); sendIntent(Aria.ACTION_PRE, -1);
sendInState2Target(ISchedulers.START); sendInState2Target(ISchedulers.START);
} }
@Override public void onResume(long resumeLocation) { @Override public void onResume(long resumeLocation) {
entity.setState(DownloadEntity.STATE_RUNNING); uploadEntity.setState(DownloadEntity.STATE_RUNNING);
sendInState2Target(DownloadSchedulers.RESUME); sendInState2Target(DownloadSchedulers.RESUME);
sendIntent(Aria.ACTION_RESUME, resumeLocation); sendIntent(Aria.ACTION_RESUME, resumeLocation);
} }
@Override public void onStop(long stopLocation) { @Override public void onStop(long stopLocation) {
entity.setState(DownloadEntity.STATE_STOP); uploadEntity.setState(DownloadEntity.STATE_STOP);
entity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.STOP); sendInState2Target(DownloadSchedulers.STOP);
sendIntent(Aria.ACTION_STOP, stopLocation); sendIntent(Aria.ACTION_STOP, stopLocation);
} }
@ -188,12 +217,11 @@ public class UploadTask implements ITask {
sendIntent.putExtra(Aria.CURRENT_SPEED, speed); sendIntent.putExtra(Aria.CURRENT_SPEED, speed);
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
if (isFirst) { if (isFirst) {
entity.setSpeed(0); speed = 0;
isFirst = false; isFirst = false;
} else {
entity.setSpeed(speed);
} }
entity.setCurrentProgress(currentLocation); handleSpeed(speed);
uploadEntity.setCurrentProgress(currentLocation);
lastLen = currentLocation; lastLen = currentLocation;
sendInState2Target(DownloadSchedulers.RUNNING); sendInState2Target(DownloadSchedulers.RUNNING);
AriaManager.APP.sendBroadcast(sendIntent); AriaManager.APP.sendBroadcast(sendIntent);
@ -201,28 +229,37 @@ public class UploadTask implements ITask {
} }
@Override public void onCancel() { @Override public void onCancel() {
entity.setState(DownloadEntity.STATE_CANCEL); uploadEntity.setState(DownloadEntity.STATE_CANCEL);
handleSpeed(0);
sendInState2Target(DownloadSchedulers.CANCEL); sendInState2Target(DownloadSchedulers.CANCEL);
sendIntent(Aria.ACTION_CANCEL, -1); sendIntent(Aria.ACTION_CANCEL, -1);
entity.deleteData(); uploadEntity.deleteData();
} }
@Override public void onComplete() { @Override public void onComplete() {
entity.setState(DownloadEntity.STATE_COMPLETE); uploadEntity.setState(DownloadEntity.STATE_COMPLETE);
entity.setComplete(true); uploadEntity.setComplete(true);
entity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.COMPLETE); sendInState2Target(DownloadSchedulers.COMPLETE);
sendIntent(Aria.ACTION_COMPLETE, entity.getFileSize()); sendIntent(Aria.ACTION_COMPLETE, uploadEntity.getFileSize());
} }
@Override public void onFail() { @Override public void onFail() {
entity.setFailNum(entity.getFailNum() + 1); uploadEntity.setFailNum(uploadEntity.getFailNum() + 1);
entity.setState(DownloadEntity.STATE_FAIL); uploadEntity.setState(DownloadEntity.STATE_FAIL);
entity.setSpeed(0); handleSpeed(0);
sendInState2Target(DownloadSchedulers.FAIL); sendInState2Target(DownloadSchedulers.FAIL);
sendIntent(Aria.ACTION_FAIL, -1); sendIntent(Aria.ACTION_FAIL, -1);
} }
private void handleSpeed(long speed) {
if (isConvertSpeed) {
uploadEntity.setConvertSpeed(CommonUtil.formatFileSize(speed) + "/s");
} else {
uploadEntity.setSpeed(speed);
}
}
/** /**
* 将任务状态发送给下载器 * 将任务状态发送给下载器
* *
@ -235,16 +272,16 @@ public class UploadTask implements ITask {
} }
private void sendIntent(String action, long location) { private void sendIntent(String action, long location) {
entity.setComplete(action.equals(Aria.ACTION_COMPLETE)); uploadEntity.setComplete(action.equals(Aria.ACTION_COMPLETE));
entity.setCurrentProgress(location); uploadEntity.setCurrentProgress(location);
entity.update(); uploadEntity.update();
if (!Configuration_1.isOpenBreadCast) return; if (!isOpenBroadCast) return;
Intent intent = CommonUtil.createIntent(AriaManager.APP.getPackageName(), action); Intent intent = CommonUtil.createIntent(context.getPackageName(), action);
intent.putExtra(Aria.ENTITY, entity); intent.putExtra(Aria.ENTITY, uploadEntity);
if (location != -1) { if (location != -1) {
intent.putExtra(Aria.CURRENT_LOCATION, location); intent.putExtra(Aria.CURRENT_LOCATION, location);
} }
AriaManager.APP.sendBroadcast(intent); context.sendBroadcast(intent);
} }
} }

@ -1,228 +0,0 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.util;
import android.util.Log;
import com.arialyy.aria.core.AriaManager;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Created by AriaL on 2016/12/8.
* 信息配置
*/
public class Configuration_1 {
private static final String TAG = "Configuration_1";
private static final String CONFIG_FILE = "/Aria/ADConfig.properties";
/**
* 当前调度器最大下载数默认最大下载数为 2
*/
private static final String DOWNLOAD_NUM = "DOWNLOAD_NUM";
/**
* 失败重试次数默认最多重试 10
*/
private static final String RE_TRY_NUM = "RE_TRY_NUM";
/**
* 是否打开下载广播默认 false
*/
private static final String OPEN_BROADCAST = "OPEN_BROADCAST";
/**
* 失败重试间隔时间默认 4000 ms
*/
private static final String RE_TRY_INTERVAL = "RE_TRY_INTERVAL";
/**
* 超时时间默认 10000 ms
*/
private static final String DOWNLOAD_TIME_OUT = "DOWNLOAD_TIME_OUT";
/**
* 设置最大速度
*/
private static final String MAX_SPEED = "MAX_SPEED";
public static boolean isOpenBreadCast = false;
private static Configuration_1 INSTANCE = null;
private File mConfigFile = null;
private static final Object LOCK = new Object();
public static Configuration_1 getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new Configuration_1();
}
}
return INSTANCE;
}
private Configuration_1() {
mConfigFile = new File(AriaManager.APP.getFilesDir().getPath() + CONFIG_FILE);
try {
if (!mConfigFile.exists()) {
mConfigFile.getParentFile().mkdirs();
mConfigFile.createNewFile();
init();
} else {
isOpenBreadCast = isOpenBroadcast();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void init() {
Map<String, String> config = new WeakHashMap<>();
config.put(DOWNLOAD_NUM, 2 + "");
config.put(RE_TRY_NUM, 10 + "");
config.put(OPEN_BROADCAST, false + "");
config.put(RE_TRY_INTERVAL, 4000 + "");
config.put(DOWNLOAD_TIME_OUT, 10000 + "");
config.put(MAX_SPEED, 64 + "");
saveConfig(config);
}
private void saveConfig(Map<String, String> config) {
if (config == null || config.size() == 0) {
return;
}
Properties properties = CommonUtil.loadConfig(mConfigFile);
Set<String> keys = config.keySet();
for (String key : keys) {
properties.setProperty(key, config.get(key));
}
CommonUtil.saveConfig(mConfigFile, properties);
}
private void save(String key, String value) {
Map<String, String> map = new WeakHashMap<>();
map.put(key, value);
saveConfig(map);
}
/**
* 设置最大下载速度
*/
public void setMaxSpeed(Speed speed) {
save(MAX_SPEED, speed.buf + "");
}
/**
* 获取最大速度
*/
public int getMaxSpeed() {
return Integer.parseInt(CommonUtil.loadConfig(mConfigFile).getProperty(MAX_SPEED, "8192"));
}
/**
* 获取下载超时时间
*
* @return 默认4000ms
*/
public int getTimeOut() {
return Integer.parseInt(CommonUtil.loadConfig(mConfigFile).getProperty(DOWNLOAD_TIME_OUT));
}
/**
* 设置重试间隔
*/
public void setTimeOut(int timeOut) {
if (timeOut < 10000) {
Log.w(TAG, "下载超时时间不能小于 10000 ms");
return;
}
save(DOWNLOAD_TIME_OUT, timeOut + "");
}
/**
* 获取失败重试间隔时间
*
* @return 默认4000ms
*/
public int getReTryInterval() {
return Integer.parseInt(CommonUtil.loadConfig(mConfigFile).getProperty(RE_TRY_INTERVAL));
}
/**
* 设置重试间隔
*/
public void setReTryInterval(int reTryInterval) {
if (reTryInterval < 4000) {
Log.w(TAG, "重试间隔不能小于4000ms");
return;
}
save(RE_TRY_INTERVAL, reTryInterval + "");
}
/**
* 获取最大下载数
*
* @return 默认返回2
*/
public int getDownloadNum() {
return Integer.parseInt(CommonUtil.loadConfig(mConfigFile).getProperty(DOWNLOAD_NUM));
}
/**
* 设置最大下载数
*/
public void setDownloadNum(int downloadNum) {
if (downloadNum < 1) {
Log.w(TAG, "最大下载数不能小于1");
return;
}
save(DOWNLOAD_NUM, downloadNum + "");
}
/**
* 获取最大重试数
*
* @return 默认返回 10
*/
public int getReTryNum() {
return Integer.parseInt(CommonUtil.loadConfig(mConfigFile).getProperty(RE_TRY_NUM));
}
/**
* 设置重试数
*/
public void setReTryNum(int reTryNum) {
if (reTryNum < 1) {
Log.w(TAG, "最大下载数不能小于1");
return;
}
save(RE_TRY_NUM, reTryNum + "");
}
/**
* 是否打开下载广播
*
* @return 默认false
*/
public boolean isOpenBroadcast() {
return Boolean.parseBoolean(CommonUtil.loadConfig(mConfigFile).getProperty(RE_TRY_NUM));
}
/**
* 设置是否打开下载广播
*/
public void setOpenBroadcast(boolean openBroadcast) {
isOpenBreadCast = openBroadcast;
save(OPEN_BROADCAST, openBroadcast + "");
}
}

@ -15,105 +15,144 @@
*/ */
package com.arialyy.aria.util; package com.arialyy.aria.util;
import android.content.Context; import android.text.TextUtils;
import android.content.pm.ApplicationInfo; import android.util.Log;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import com.arialyy.aria.window.FileEntity; import com.arialyy.aria.window.FileEntity;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Created by Aria.Lao on 2017/3/21. * Created by Aria.Lao on 2017/3/21.
*/ */
public class FileUtil { public class FileUtil {
Context mContext; private static final String TAG = "FileUtil";
public FileUtil(Context context) { /**
mContext = context; * 通过流创建文件
*/
public static void createFileFormInputStream(InputStream is, String path) {
try {
FileOutputStream fos = new FileOutputStream(path);
byte[] buf = new byte[1376];
while (is.read(buf) > 0) {
fos.write(buf, 0, buf.length);
}
is.close();
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
/** /**
* 文件列表 * 校验文件MD5码
*/ */
public List<FileEntity> loadFiles(String path) { public static boolean checkMD5(String md5, File updateFile) {
File file = new File(path); if (TextUtils.isEmpty(md5) || updateFile == null) {
File[] files = file.listFiles(); Log.e(TAG, "MD5 string empty or updateFile null");
List<FileEntity> list = new ArrayList<>(); return false;
for (File f : files) {
FileEntity entity = new FileEntity();
entity.fileName = f.getName();
//entity.fileInfo = getFileType(f.getPath());
//entity.fileDrawable = getApkIcon(mContext, f.getPath());
list.add(entity);
} }
return list;
String calculatedDigest = getFileMD5(updateFile);
if (calculatedDigest == null) {
Log.e(TAG, "calculatedDigest null");
return false;
}
return calculatedDigest.equalsIgnoreCase(md5);
} }
/** /**
* 获取文件类型 * 校验文件MD5码
*/ */
public FileType getFileType(String path) { public static boolean checkMD5(String md5, InputStream is) {
String exName = getExName(path); if (TextUtils.isEmpty(md5) || is == null) {
String type = ""; Log.e(TAG, "MD5 string empty or updateFile null");
FileType fType = null; return false;
if (exName.equalsIgnoreCase("apk")) { }
fType = new FileType("应用", getApkIcon(path));
} else if (exName.equalsIgnoreCase("img") String calculatedDigest = getFileMD5(is);
|| exName.equalsIgnoreCase("png") if (calculatedDigest == null) {
|| exName.equalsIgnoreCase("jpg") Log.e(TAG, "calculatedDigest null");
|| exName.equalsIgnoreCase("jepg")) { return false;
//fType = new FileType("图片", )
} else if (exName.equalsIgnoreCase("mp3") || exName.equalsIgnoreCase("wm")) {
//fType = new FileType("音乐", );
} else if (exName.equalsIgnoreCase("mp4")
|| exName.equalsIgnoreCase("rm")
|| exName.equalsIgnoreCase("rmvb")) {
//fType = new FileType("视频", );
} }
return fType; return calculatedDigest.equalsIgnoreCase(md5);
} }
/** /**
* 获取扩展名 * 获取文件MD5码
*/ */
public String getExName(String path) { public static String getFileMD5(File updateFile) {
int separatorIndex = path.lastIndexOf("."); InputStream is;
return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length()); try {
is = new FileInputStream(updateFile);
} catch (FileNotFoundException e) {
Log.e(TAG, "Exception while getting FileInputStream", e);
return null;
}
return getFileMD5(is);
} }
/** /**
* 获取apk文件的icon * 获取文件MD5码
*
* @param path apk文件路径
*/ */
public Drawable getApkIcon(String path) { public static String getFileMD5(InputStream is) {
PackageManager pm = mContext.getPackageManager(); MessageDigest digest;
PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES); try {
if (info != null) { digest = MessageDigest.getInstance("MD5");
ApplicationInfo appInfo = info.applicationInfo; } catch (NoSuchAlgorithmException e) {
//android有bug,需要下面这两句话来修复才能获取apk图片 Log.e(TAG, "Exception while getting digest", e);
appInfo.sourceDir = path; return null;
appInfo.publicSourceDir = path;
// String packageName = appInfo.packageName; //得到安装包名称
// String version=info.versionName; //得到版本信息
return pm.getApplicationIcon(appInfo);
} }
return null;
}
class FileType { byte[] buffer = new byte[8192];
String name; int read;
Drawable icon; try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
// Fill to 32 chars
output = String.format("%32s", output).replace(' ', '0');
return output;
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e(TAG, "Exception on closing MD5 input stream", e);
}
}
}
public FileType(String name, Drawable icon) { /**
this.name = name; * 文件列表
this.icon = icon; */
public List<FileEntity> loadFiles(String path) {
File file = new File(path);
File[] files = file.listFiles();
List<FileEntity> list = new ArrayList<>();
for (File f : files) {
FileEntity entity = new FileEntity();
entity.fileName = f.getName();
//entity.fileInfo = getFileType(f.getPath());
//entity.fileDrawable = getApkIcon(mContext, f.getPath());
list.add(entity);
} }
return list;
} }
} }

@ -0,0 +1,113 @@
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.util;
import android.util.Log;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by AriaLyy@outlook.com on 2015/7/30.
* 反射工具类
*/
public class ReflectionUtil {
private static final String TAG = "ReflectionUtil";
/**
* 获取类里面的所在字段
*/
public static Field[] getFields(Class clazz) {
Field[] fields = null;
fields = clazz.getDeclaredFields();
if (fields == null || fields.length == 0) {
Class superClazz = clazz.getSuperclass();
if (superClazz != null) {
fields = getFields(superClazz);
}
}
return fields;
}
/**
* 获取所有字段包括父类的字段
*/
public static List<Field> getAllFields(Class clazz) {
List<Field> fields = new ArrayList<>();
Class personClazz = clazz.getSuperclass();
if (personClazz != null) {
Collections.addAll(fields, personClazz.getDeclaredFields());
}
Collections.addAll(fields, clazz.getDeclaredFields());
return fields;
}
/**
* 获取类里面的指定对象如果该类没有则从父类查询
*/
public static Field getField(Class clazz, String name) {
Field field = null;
try {
field = clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
try {
field = clazz.getField(name);
} catch (NoSuchFieldException e1) {
if (clazz.getSuperclass() == null) {
return field;
} else {
field = getField(clazz.getSuperclass(), name);
}
}
}
if (field != null) {
field.setAccessible(true);
}
return field;
}
/**
* 利用递归找一个类的指定方法如果找不到去父亲里面找直到最上层Object对象为止
*
* @param clazz 目标类
* @param methodName 方法名
* @param params 方法参数类型数组
* @return 方法对象
*/
public static Method getMethod(Class clazz, String methodName, final Class<?>... params) {
Method method = null;
try {
method = clazz.getDeclaredMethod(methodName, params);
} catch (NoSuchMethodException e) {
try {
method = clazz.getMethod(methodName, params);
} catch (NoSuchMethodException ex) {
if (clazz.getSuperclass() == null) {
Log.e(TAG, "无法找到" + methodName + "方法");
return method;
} else {
method = getMethod(clazz.getSuperclass(), methodName, params);
}
}
}
if (method != null) {
method.setAccessible(true);
}
return method;
}
}

@ -1,15 +1,20 @@
# Aria # Aria
![图标](https://github.com/AriaLyy/DownloadUtil/blob/v_2.0/app/src/main/res/mipmap-hdpi/ic_launcher.png)</br> ![图标](https://github.com/AriaLyy/DownloadUtil/blob/v_2.0/app/src/main/res/mipmap-hdpi/ic_launcher.png)</br>
Aria,让上传、下载更容易实现</br> Aria项目源于15年工作中遇到的一个文件下载管理的需求,当时被下载折磨的痛不欲生,从那时起便萌生了编写一个简单易用,稳当高效的下载框架,aria经历了1.0到3.0的开发,算是越来越接近当初所制定的目标了。
Aria有以下特点: Aria有以下特点:
- 简单 + 简单、方便
- 可在Dialog、popupWindow等组件中使用 - 可以在Activity、Service、Fragment、Dialog、popupWindow、Notification等组件中使用
- 支持多线程、多任务下载 - 支持任务自动调度,使用者不需要关心任务状态切换的逻辑
- 支持多任务自动调度 - [通过Aria的事件,能很容易获取当前下载任务的下载状态](#下载状态获取)
- 可以直接获取速度 - [一句代码加可以获取当前的下载速度](#常用接口)
- 支持https地址下载 - [一句代码就可以动态设置最大下载数](#代码中设置参数)
- 支持上传操作 - [通过修改配置文件很容易就能修改下载线程数](#配置文件设置参数)
+ 支持https地址下载
- 在配置文件中很容易就可以设置CA证书的信息
+ 支持300、301、302重定向下载链接下载
+ 支持上传操作
Aria怎样使用? Aria怎样使用?
* [下载](#使用) * [下载](#使用)
@ -20,7 +25,7 @@ Aria怎样使用?
## 下载 ## 下载
[![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)</br> [![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)</br>
```java ```java
compile 'com.arialyy.aria:Aria:3.0.3' compile 'com.arialyy.aria:Aria:3.1.0'
``` ```
## 示例 ## 示例
@ -72,7 +77,8 @@ compile 'com.arialyy.aria:Aria:3.0.3'
Aria.download(this).load(DOWNLOAD_URL).cancel(); Aria.download(this).load(DOWNLOAD_URL).cancel();
``` ```
### 二、如果你希望读取下载进度或下载信息,那么你需要创建事件类,并在onResume(Activity、Fragment)或构造函数(Dialog、PopupWindow),将该事件类注册到Aria管理器。 ### 下载状态获取
如果你希望读取下载进度或下载信息,那么你需要创建事件类,并在onResume(Activity、Fragment)或构造函数(Dialog、PopupWindow),将该事件类注册到Aria管理器。
* 创建事件类 * 创建事件类
```java ```java
@ -104,8 +110,107 @@ compile 'com.arialyy.aria:Aria:3.0.3'
} }
``` ```
### 关于下载的其它api ### Aria参数配置
[Download API](https://github.com/AriaLyy/Aria/blob/master/DownloadApi.md) #### 配置文件设置参数
创建`aria_config.xml`文件,将其放在`assets`目录下,添加以下内容
```xml
<?xml version="1.0" encoding="utf-8"?>
<aria>
<!--注意,修改该配置文件中的属性会覆盖代码中所设置的属性-->
<download>
<!--设置下载线程,线程下载数改变后,新的下载任务才会生效-->
<threadNum value="4"/>
<!--是否打开下载广播,默认为false-->
<openBroadcast value="false"/>
<!--设置下载队列最大任务数, 默认为2-->
<maxTaskNum value="2"/>
<!--设置下载失败,重试次数,默认为10-->
<reTryNum value="10"/>
<!--设置重试间隔,单位为毫秒,默认2000毫秒-->
<reTryInterval value="2000"/>
<!--设置url连接超时时间,单位为毫秒,默认5000毫秒-->
<connectTimeOut value="5000"/>
<!--设置IO流读取时间,单位为毫秒,默认20000毫秒,该时间不能少于10000毫秒-->
<iOTimeOut value="20000"/>
<!--设置写文件buff大小,该数值大小不能小于2048,数值变小,下载速度会变慢-->
<buffSize value="8192"/>
<!--设置https ca 证书信息;path 为assets目录下的CA证书完整路径,name 为CA证书名-->
<ca name="" path=""/>
<!--是否需要转换速度单位,转换完成后为:1b/s、1k/s、1m/s、1g/s、1t/s,如果不需要将返回byte长度-->
<cnvertSpeed value="false"/>
</download>
<upload>
<!--是否打开上传广播,默认为false-->
<openBroadcast value="false"/>
<!--设置上传队列最大任务数, 默认为2-->
<maxTaskNum value="2"/>
<!--设置上传失败,重试次数,默认为10-->
<reTryNum value="10"/>
<!--设置重试间隔,单位为毫秒-->
<reTryInterval value="2000"/>
<!--设置url连接超时时间,单位为毫秒,默认5000毫秒-->
<connectTimeOut value="5000"/>
</upload>
</aria>
```
#### 代码中设置参数
除了文件方式外修改Aria参数外,同样的,你也可以在代码中动态修改Aria参数</br>
通过`Aria.get(this).getDownloadConfig()`或`Aria.get(this).getUploadConfig()`直接获取配置文件,然后修改参数</br>
如以下所示:
```java
// 修改最大下载数,调用完成后,立即生效
// 如当前下载任务数是4,修改完成后,当前任务数会被Aria自动调度任务数
Aria.get(this).getDownloadConfig().setMaxTaskNum(3);
```
### 常用接口
* 停止所有任务
```java
Aria.download(this).stopAllTask();
```
* 删除所有任务
```java
Aria.download(this).removeAllTask();
```
* 获取当前任务的下载速度
速度参数有点特殊,需要[下载事件支持](#下载状态获取)
``` java
@Override public void onTaskRunning(DownloadTask task) {
//如果你打开了速度单位转换配置,将可以通过以下方法获取带单位的下载速度,如:1 m/s
String convertSpeed = task.getConvertSpeed();
//如果你有自己的单位格式,可以通过以下方法获取原始byte长度
long speed = task.getSpeed();
}
```
* 获取下载的文件大小
同样的,你也可以在DownloadTask对象中获取下载的文件大小
```
@Override public void onTaskRunning(DownloadTask task) {
 //获取文件大小
long fileSize = task.getFileSize();
}
```
**tips:为了防止内存泄露的情况,事件类需要使用staic进行修饰** **tips:为了防止内存泄露的情况,事件类需要使用staic进行修饰**
@ -132,9 +237,7 @@ compile 'com.arialyy.aria:Aria:3.0.3'
* 取消上传 * 取消上传
```java ```java
Aria.upload(this) Aria.upload(this).load(filePath).cancel();
.load(filePath)
.cancel();
``` ```
## 混淆配置 ## 混淆配置
@ -148,7 +251,11 @@ compile 'com.arialyy.aria:Aria:3.0.3'
*** ***
## 后续版本开发规划
* ~~实现上传队列调度功能~~
## 开发日志 ## 开发日志
+ v_3.1.0 添加Aria配置文件,优化代码
+ v_3.0.3 修复暂停后删除任务,闪退问题,添加删除记录的api + v_3.0.3 修复暂停后删除任务,闪退问题,添加删除记录的api
+ v_3.0.2 支持30x重定向链接下载 + v_3.0.2 支持30x重定向链接下载
+ v_3.0.0 添加上传任务支持,修复一些已发现的bug + v_3.0.0 添加上传任务支持,修复一些已发现的bug

@ -1,13 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<aria> <aria>
<!--注意,修改该配置文件中的属性会覆盖代码中所设置的属性-->
<download> <download>
<!--设置下载线程,线程下载数改变后,新的下载任务才会生效-->
<threadNum value="4"/>
<!--是否打开下载广播,默认为false--> <!--是否打开下载广播,默认为false-->
<openBroadcast value="false"/> <openBroadcast value="false"/>
<!--设置下载队列最大任务数, 默认为2--> <!--设置下载队列最大任务数, 默认为2-->
<maxQueueNum value="2"/> <maxTaskNum value="2"/>
<!--设置下载失败,重试次数,默认为10--> <!--设置下载失败,重试次数,默认为10-->
<reTryNum value="10"/> <reTryNum value="10"/>
@ -15,8 +19,11 @@
<!--设置重试间隔,单位为毫秒,默认2000毫秒--> <!--设置重试间隔,单位为毫秒,默认2000毫秒-->
<reTryInterval value="2000"/> <reTryInterval value="2000"/>
<!--设置url连接超时时间,单位为毫秒,默认5000毫秒-->
<connectTimeOut value="5000"/>
<!--设置IO流读取时间,单位为毫秒,默认20000毫秒,该时间不能少于10000毫秒--> <!--设置IO流读取时间,单位为毫秒,默认20000毫秒,该时间不能少于10000毫秒-->
<readTimeout value="20000"/> <iOTimeOut value="20000"/>
<!--设置写文件buff大小,该数值大小不能小于2048,数值变小,下载速度会变慢--> <!--设置写文件buff大小,该数值大小不能小于2048,数值变小,下载速度会变慢-->
<buffSize value="8192"/> <buffSize value="8192"/>
@ -24,6 +31,9 @@
<!--设置https ca 证书信息;path 为assets目录下的CA证书完整路径,name 为CA证书名--> <!--设置https ca 证书信息;path 为assets目录下的CA证书完整路径,name 为CA证书名-->
<ca name="" path=""/> <ca name="" path=""/>
<!--是否需要转换速度单位,转换完成后为:1b/s、1k/s、1m/s、1g/s、1t/s,如果不需要将返回byte长度-->
<convertSpeed value="true"/>
</download> </download>
<upload> <upload>
@ -31,7 +41,7 @@
<openBroadcast value="false"/> <openBroadcast value="false"/>
<!--设置上传队列最大任务数, 默认为2--> <!--设置上传队列最大任务数, 默认为2-->
<maxQueueNum value="2"/> <maxTaskNum value="2"/>
<!--设置上传失败,重试次数,默认为10--> <!--设置上传失败,重试次数,默认为10-->
<reTryNum value="10"/> <reTryNum value="10"/>

@ -22,6 +22,7 @@ import android.support.v7.widget.Toolbar;
import android.view.View; import android.view.View;
import butterknife.Bind; import butterknife.Bind;
import butterknife.OnClick; import butterknife.OnClick;
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;

@ -44,7 +44,7 @@ public class DownloadDialog extends AbsDialog {
@Bind(R.id.speed) TextView mSpeed; @Bind(R.id.speed) TextView mSpeed;
private static final String DOWNLOAD_URL = private static final String DOWNLOAD_URL =
"http://static.gaoshouyou.com/d/3a/93/573ae1db9493a801c24bf66128b11e39.apk"; "http://clashroyalecdn.static.kunlun.com/Clash_Royale-1.2.6-kunlun_landing_page-release.apk.apk";
public DownloadDialog(Context context) { public DownloadDialog(Context context) {
super(context); super(context);
@ -110,14 +110,14 @@ public class DownloadDialog extends AbsDialog {
@Override public void onTaskStop(DownloadTask task) { @Override public void onTaskStop(DownloadTask task) {
super.onTaskStop(task); super.onTaskStop(task);
setBtState(true); setBtState(true);
mSpeed.setText("0.0kb/s"); mSpeed.setText(task.getConvertSpeed());
} }
@Override public void onTaskCancel(DownloadTask task) { @Override public void onTaskCancel(DownloadTask task) {
super.onTaskCancel(task); super.onTaskCancel(task);
setBtState(true); setBtState(true);
mPb.setProgress(0); mPb.setProgress(0);
mSpeed.setText("0.0kb/s"); mSpeed.setText(task.getConvertSpeed());
} }
@Override public void onTaskRunning(DownloadTask task) { @Override public void onTaskRunning(DownloadTask task) {
@ -129,7 +129,7 @@ public class DownloadDialog extends AbsDialog {
} else { } else {
mPb.setProgress((int) ((current * 100) / len)); mPb.setProgress((int) ((current * 100) / len));
} }
mSpeed.setText(CommonUtil.formatFileSize(task.getSpeed()) + "/s"); mSpeed.setText(task.getConvertSpeed());
} }
} }
} }

@ -131,7 +131,7 @@ public class DownloadPopupWindow extends AbsPopupWindow {
} else { } else {
mPb.setProgress((int) ((current * 100) / len)); mPb.setProgress((int) ((current * 100) / len));
} }
mSpeed.setText(CommonUtil.formatFileSize(task.getSpeed()) + "/s"); mSpeed.setText(task.getConvertSpeed());
} }
} }
} }

@ -56,7 +56,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
//"http://kotlinlang.org/docs/kotlin-docs.pdf"; //"http://kotlinlang.org/docs/kotlin-docs.pdf";
//"https://atom-installer.github.com/v1.13.0/AtomSetup.exe?s=1484074138&ext=.exe"; //"https://atom-installer.github.com/v1.13.0/AtomSetup.exe?s=1484074138&ext=.exe";
"http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk"; "http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk";
//"http://static.gaoshouyou.com/d/36/69/2d3699acfa69e9632262442c46516ad8.apk"; //"http://static.gaoshouyou.com/d/36/69/2d3699acfa69e9632262442c46516ad8.apk";
//不支持断点的链接 //不支持断点的链接
//"http://ox.konsung.net:5555/ksdc-web/download/downloadFile/?fileName=ksdc_1.0.2.apk&rRange=0-"; //"http://ox.konsung.net:5555/ksdc-web/download/downloadFile/?fileName=ksdc_1.0.2.apk&rRange=0-";
//"http://172.18.104.50:8080/download/_302turn"; //"http://172.18.104.50:8080/download/_302turn";
@ -91,7 +91,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
} else { } else {
mPb.setProgress((int) ((current * 100) / len)); mPb.setProgress((int) ((current * 100) / len));
} }
mSpeed.setText(CommonUtil.formatFileSize(task.getSpeed()) + "/s"); mSpeed.setText(task.getConvertSpeed());
break; break;
case DOWNLOAD_PRE: case DOWNLOAD_PRE:
mSize.setText(CommonUtil.formatFileSize((Long) msg.obj)); mSize.setText(CommonUtil.formatFileSize((Long) msg.obj));
@ -164,7 +164,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
toolbar.setTitle("单任务下载"); toolbar.setTitle("单任务下载");
init(); init();
Aria.get(this).openBroadcast(true); Aria.get(this).getDownloadConfig().setOpenBreadCast(true);
} }
private void init() { private void init() {
@ -173,33 +173,33 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
int p = (int) (target.getCurrentProgress() * 100 / target.getFileSize()); int p = (int) (target.getCurrentProgress() * 100 / target.getFileSize());
mPb.setProgress(p); mPb.setProgress(p);
} }
mRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { //mRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override public void onCheckedChanged(RadioGroup group, int checkedId) { // @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) { // switch (checkedId) {
case 1: // case 1:
Aria.get(this).setMaxSpeed(Speed.KB_256); // Aria.get(this).setMaxSpeed(Speed.KB_256);
break; // break;
case 2: // case 2:
Aria.get(this).setMaxSpeed(Speed.KB_512); // Aria.get(this).setMaxSpeed(Speed.KB_512);
break; // break;
case 3: // case 3:
Aria.get(this).setMaxSpeed(Speed.MB_1); // Aria.get(this).setMaxSpeed(Speed.MB_1);
break; // break;
case 4: // case 4:
Aria.get(this).setMaxSpeed(Speed.MB_2); // Aria.get(this).setMaxSpeed(Speed.MB_2);
break; // break;
case 5: // case 5:
Aria.get(this).setMaxSpeed(Speed.MAX); // Aria.get(this).setMaxSpeed(Speed.MAX);
break; // break;
} // }
stop(); // stop();
new Handler().postDelayed(new Runnable() { // new Handler().postDelayed(new Runnable() {
@Override public void run() { // @Override public void run() {
start(); // start();
} // }
}, 2000); // }, 2000);
} // }
}); //});
} }
public void onClick(View view) { public void onClick(View view) {

@ -45,7 +45,7 @@ public class DownloadFragment extends AbsFragment<FragmentDownloadBinding> {
@Bind(R.id.speed) TextView mSpeed; @Bind(R.id.speed) TextView mSpeed;
private static final String DOWNLOAD_URL = private static final String DOWNLOAD_URL =
"http://static.gaoshouyou.com/d/3a/93/573ae1db9493a801c24bf66128b11e39.apk"; "http://rs.0.gaoshouyou.com/d/90/d7/7490c6fd6cd733bef336e766778507c5.apk";
@Override protected void init(Bundle savedInstanceState) { @Override protected void init(Bundle savedInstanceState) {
if (Aria.download(this).taskExists(DOWNLOAD_URL)) { if (Aria.download(this).taskExists(DOWNLOAD_URL)) {
@ -74,7 +74,6 @@ public class DownloadFragment extends AbsFragment<FragmentDownloadBinding> {
Aria.download(this) Aria.download(this)
.load(DOWNLOAD_URL) .load(DOWNLOAD_URL)
.setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/daialog.apk") .setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/daialog.apk")
.setDownloadName("daialog.apk")
.start(); .start();
break; break;
case R.id.stop: case R.id.stop:
@ -134,7 +133,7 @@ public class DownloadFragment extends AbsFragment<FragmentDownloadBinding> {
} else { } else {
mPb.setProgress((int) ((current * 100) / len)); mPb.setProgress((int) ((current * 100) / len));
} }
mSpeed.setText(CommonUtil.formatFileSize(task.getSpeed()) + "/s"); mSpeed.setText(task.getConvertSpeed());
} }
} }
} }

@ -103,7 +103,6 @@ final class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapter
long size = item.getFileSize(); long size = item.getFileSize();
int current = 0; int current = 0;
long progress = item.getCurrentProgress(); long progress = item.getCurrentProgress();
long speed = item.getSpeed();
current = size == 0 ? 0 : (int) (progress * 100 / size); current = size == 0 ? 0 : (int) (progress * 100 / size);
holder.progress.setProgress(current); holder.progress.setProgress(current);
BtClickListener listener = new BtClickListener(item); BtClickListener listener = new BtClickListener(item);
@ -136,7 +135,7 @@ final class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapter
} }
holder.bt.setText(str); holder.bt.setText(str);
holder.bt.setTextColor(getColor(color)); holder.bt.setTextColor(getColor(color));
holder.speed.setText(CommonUtil.formatFileSize(speed) + "/s"); holder.speed.setText(item.getConvertSpeed());
holder.fileSize.setText(covertCurrentSize(progress) + "/" + CommonUtil.formatFileSize(size)); holder.fileSize.setText(covertCurrentSize(progress) + "/" + CommonUtil.formatFileSize(size));
holder.cancel.setOnClickListener(new View.OnClickListener() { holder.cancel.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { @Override public void onClick(View v) {
@ -147,10 +146,6 @@ final class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapter
}); });
} }
public void setDownloadNum(int num) {
Aria.get(getContext()).setMaxDownloadNum(num);
}
private String covertCurrentSize(long currentSize) { private String covertCurrentSize(long currentSize) {
String size = CommonUtil.formatFileSize(currentSize); String size = CommonUtil.formatFileSize(currentSize);
return size.substring(0, size.length() - 1); return size.substring(0, size.length() - 1);

@ -83,7 +83,7 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
@Override protected void dataCallback(int result, Object data) { @Override protected void dataCallback(int result, Object data) {
super.dataCallback(result, data); super.dataCallback(result, data);
if (result == DownloadNumDialog.RESULT_CODE) { if (result == DownloadNumDialog.RESULT_CODE) {
Aria.get(this).setMaxDownloadNum(Integer.parseInt(data + "")); Aria.get(this).getDownloadConfig().setMaxTaskNum(Integer.parseInt(data + ""));
} }
} }

@ -31,11 +31,7 @@ import com.arialyy.frame.util.show.T;
public class DownloadService extends Service { public class DownloadService extends Service {
private static final String DOWNLOAD_URL = private static final String DOWNLOAD_URL =
//"http://kotlinlang.org/docs/kotlin-docs.pdf"; "http://rs.0.gaoshouyou.com/d/df/db/03df9eab61dbc48a5939f671f05f1cdf.apk";
//"https://atom-installer.github.com/v1.13.0/AtomSetup.exe?s=1484074138&ext=.exe";
//"http://static.gaoshouyou.com/d/21/e8/61218d78d0e8b79df68dbc18dd484c97.apk";
//不支持断点的链接
"http://ox.konsung.net:5555/ksdc-web/download/downloadFile/?fileName=ksdc_1.0.2.apk&rRange=0-";
private DownloadNotification mNotify; private DownloadNotification mNotify;
@Nullable @Override public IBinder onBind(Intent intent) { @Nullable @Override public IBinder onBind(Intent intent) {

@ -25,7 +25,7 @@
</string-array> </string-array>
<string-array name="download_url"> <string-array name="download_url">
<item>http://g37.gdl.netease.com/onmyoji_netease_1.apk</item> <item>https://g37.gdl.netease.com/onmyoji_netease_10_1.0.20.apk</item>
<item>http://static.gaoshouyou.com/d/eb/f2/dfeba30541f209ab8a50d847fc1661ce.apk</item> <item>http://static.gaoshouyou.com/d/eb/f2/dfeba30541f209ab8a50d847fc1661ce.apk</item>
<item>http://rs.0.gaoshouyou.com/d/51/46/58514d126c46b8a3f27fc8c7db3b09ec.apk</item> <item>http://rs.0.gaoshouyou.com/d/51/46/58514d126c46b8a3f27fc8c7db3b09ec.apk</item>
<item>http://rs.0.gaoshouyou.com/d/23/69/07238f952669727878d7a0e180534c8b.apk</item> <item>http://rs.0.gaoshouyou.com/d/23/69/07238f952669727878d7a0e180534c8b.apk</item>

@ -13,7 +13,3 @@
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true # org.gradle.parallel=true
#Wed Dec 07 20:19:22 CST 2016 #Wed Dec 07 20:19:22 CST 2016
systemProp.http.proxyPassword=7RbgsDfOoBn
systemProp.http.proxyHost=hilton.h.xduotai.com
systemProp.http.proxyUser=duotai
systemProp.http.proxyPort=10969

Loading…
Cancel
Save