优化配置文件的读取

v3.6.6
laoyuyu 6 years ago
parent 9fc5f47a6b
commit bd1b3e7416
  1. 11
      Aria/src/main/java/com/arialyy/aria/core/AriaManager.java
  2. 15
      Aria/src/main/java/com/arialyy/aria/core/ConfigHelper.java
  3. 8
      Aria/src/main/java/com/arialyy/aria/core/download/BaseDListener.java
  4. 11
      Aria/src/main/java/com/arialyy/aria/core/upload/BaseUListener.java
  5. 110
      Aria/src/main/java/com/arialyy/aria/util/CommonUtil.java
  6. 1
      DEV_LOG.md
  7. 2
      app/src/main/assets/aria_config.xml
  8. 19
      app/src/main/java/com/arialyy/simple/download/SingleTaskActivity.java
  9. 2
      app/src/main/java/com/arialyy/simple/upload/HttpUploadActivity.java
  10. 309
      aria/src/main/java/com/arialyy/aria/core/Configuration.java

@ -130,7 +130,7 @@ import org.xml.sax.SAXException;
DownloadEntity.class, UploadEntity.class, DownloadGroupEntity.class, DownloadEntity.class, UploadEntity.class, DownloadGroupEntity.class,
DownloadTaskEntity.class, UploadTaskEntity.class, DownloadGroupTaskEntity.class DownloadTaskEntity.class, UploadTaskEntity.class, DownloadGroupTaskEntity.class
}; };
String sql = "UPDATE %s SET state=2 WHERE state in (3,4,5,6)"; String sql = "UPDATE %s SET state=2 WHERE state IN (3,4,5,6)";
for (Class clazz : clazzs) { for (Class clazz : clazzs) {
String temp = String.format(sql, clazz.getSimpleName()); String temp = String.format(sql, clazz.getSimpleName());
DbEntity.exeSql(temp); DbEntity.exeSql(temp);
@ -376,6 +376,10 @@ import org.xml.sax.SAXException;
* 初始化配置文件 * 初始化配置文件
*/ */
private void initConfig() { private void initConfig() {
mDConfig = Configuration.getInstance().downloadCfg;
mUConfig = Configuration.getInstance().uploadCfg;
mAConfig = Configuration.getInstance().appCfg;
File xmlFile = new File(APP.getFilesDir().getPath() + Configuration.XML_FILE); File xmlFile = new File(APP.getFilesDir().getPath() + Configuration.XML_FILE);
File tempDir = new File(APP.getFilesDir().getPath() + "/temp"); File tempDir = new File(APP.getFilesDir().getPath() + "/temp");
if (!xmlFile.exists()) { if (!xmlFile.exists()) {
@ -389,16 +393,13 @@ import org.xml.sax.SAXException;
} }
CommonUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"), CommonUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"),
file.getPath()); file.getPath());
if (!CommonUtil.checkMD5(md5Code, file)) { if (!CommonUtil.checkMD5(md5Code, file) || !Configuration.getInstance().configExists()) {
loadConfig(); loadConfig();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
mDConfig = Configuration.DownloadConfig.getInstance();
mUConfig = Configuration.UploadConfig.getInstance();
mAConfig = Configuration.AppConfig.getInstance();
if (tempDir.exists()) { if (tempDir.exists()) {
File newDir = new File(APP.getFilesDir().getPath() + DOWNLOAD_TEMP_DIR); File newDir = new File(APP.getFilesDir().getPath() + DOWNLOAD_TEMP_DIR);
newDir.mkdirs(); newDir.mkdirs();

@ -22,15 +22,14 @@ import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
/** /**
* Created by lyy on 2017/5/22. * Created by lyy on 2017/5/22. 读取配置文件
* 读取配置文件
*/ */
class ConfigHelper extends DefaultHandler { class ConfigHelper extends DefaultHandler {
private final String TAG = "ConfigHelper"; private final String TAG = "ConfigHelper";
private Configuration.DownloadConfig mDownloadConfig = Configuration.DownloadConfig.getInstance(); private Configuration.DownloadConfig mDownloadConfig = Configuration.getInstance().downloadCfg;
private Configuration.UploadConfig mUploadConfig = Configuration.UploadConfig.getInstance(); private Configuration.UploadConfig mUploadConfig = Configuration.getInstance().uploadCfg;
private Configuration.AppConfig mAppConfig = Configuration.AppConfig.getInstance(); private Configuration.AppConfig mAppConfig = Configuration.getInstance().appCfg;
private @ConfigType int mType; private @ConfigType int mType;
@Override public void startDocument() throws SAXException { @Override public void startDocument() throws SAXException {
@ -357,8 +356,8 @@ class ConfigHelper extends DefaultHandler {
@Override public void endDocument() throws SAXException { @Override public void endDocument() throws SAXException {
super.endDocument(); super.endDocument();
mDownloadConfig.saveAll(); mDownloadConfig.save();
mUploadConfig.saveAll(); mUploadConfig.save();
mAppConfig.saveAll(); mAppConfig.save();
} }
} }

@ -57,13 +57,7 @@ public class BaseDListener extends BaseListener<DownloadEntity, DownloadTaskEnti
mEntity.setComplete(state == IEntity.STATE_COMPLETE); mEntity.setComplete(state == IEntity.STATE_COMPLETE);
if (state == IEntity.STATE_CANCEL) { if (state == IEntity.STATE_CANCEL) {
if (mEntity instanceof DownloadEntity) { if (mEntity instanceof DownloadEntity) {
TaskRecord record = CommonUtil.delTaskRecord(mEntity.getDownloadPath(), 1, mTaskEntity.isRemoveFile());
DbEntity.findFirst(TaskRecord.class, "TaskRecord.filePath=?", mTaskEntity.getKey());
if (record != null) {
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), mEntity);
} else {
CommonUtil.delTaskRecord(mEntity.getDownloadPath(), 1, mTaskEntity.isRemoveFile());
}
} }
return; return;
} else if (state == IEntity.STATE_STOP) { } else if (state == IEntity.STATE_STOP) {

@ -42,17 +42,8 @@ class BaseUListener extends BaseListener<UploadEntity, UploadTaskEntity, UploadT
mEntity.setComplete(state == IEntity.STATE_COMPLETE); mEntity.setComplete(state == IEntity.STATE_COMPLETE);
if (state == IEntity.STATE_CANCEL) { if (state == IEntity.STATE_CANCEL) {
if (mEntity instanceof UploadEntity) { if (mEntity instanceof UploadEntity) {
TaskRecord record = CommonUtil.delTaskRecord(mEntity.getFilePath(), 2, mTaskEntity.isRemoveFile());
DbEntity.findFirst(TaskRecord.class, "TaskRecord.filePath=?", mTaskEntity.getKey());
if (record != null) {
CommonUtil.delTaskRecord(record, mTaskEntity.isRemoveFile(), mEntity);
}else {
CommonUtil.delTaskRecord(mEntity.getFilePath(), 2, mTaskEntity.isRemoveFile());
}
} }
//else if (mEntity instanceof AbsGroupEntity) {
// CommonUtil.delGroupTaskRecord(mTaskEntity.isRemoveFile(), ((AbsGroupEntity) mEntity));
//}
return; return;
} else if (state == IEntity.STATE_STOP) { } else if (state == IEntity.STATE_STOP) {
mEntity.setStopTime(System.currentTimeMillis()); mEntity.setStopTime(System.currentTimeMillis());

@ -50,6 +50,9 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
@ -76,6 +79,102 @@ import java.util.regex.Pattern;
public class CommonUtil { public class CommonUtil {
private static final String TAG = "CommonUtil"; private static final String TAG = "CommonUtil";
/**
* 删除文件
* @param path 文件路径
* @return {@code true}删除成功{@co'de false}删除失败
*/
public static boolean deleteFile(String path){
if (TextUtils.isEmpty(path)){
ALog.e(TAG, "删除文件失败,路径为空");
return false;
}
File file = new File(path);
if (file.exists()) {
final File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
if (file.renameTo(to)) {
return to.delete();
} else {
return file.delete();
}
}
return false;
}
/**
* 将对象写入文件
*
* @param filePath 文件路径
* @param data data数据必须实现{@link Serializable}接口
*/
public static void writeObjToFile(String filePath, Object data) {
if (!(data instanceof Serializable)) {
ALog.e(TAG, "对象写入文件失败,data数据必须实现Serializable接口");
return;
}
FileOutputStream ops = null;
try {
if (!createFile(filePath)) {
return;
}
ops = new FileOutputStream(filePath);
ObjectOutputStream oops = new ObjectOutputStream(ops);
oops.writeObject(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ops != null) {
try {
ops.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 从文件中读取对象
*
* @param filePath 文件路径
* @return 如果读取成功返回相应的Obj对象读取失败返回null
*/
public static Object readObjFromFile(String filePath) {
if (TextUtils.isEmpty(filePath)) {
ALog.e(TAG, "文件路径为空");
return null;
}
File file = new File(filePath);
if (!file.exists()) {
ALog.e(TAG, String.format("文件【%s】不存在", filePath));
return null;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(filePath);
ObjectInputStream oois = new ObjectInputStream(fis);
Object obj = oois.readObject();
return obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/** /**
* 获取分块文件的快大小 * 获取分块文件的快大小
* *
@ -583,7 +682,7 @@ public class CommonUtil {
TaskRecord record = DbEntity.findFirst(TaskRecord.class, "filePath=?", filePath); TaskRecord record = DbEntity.findFirst(TaskRecord.class, "filePath=?", filePath);
File file = new File(filePath); File file = new File(filePath);
if (record == null) { if (record == null) {
ALog.w(TAG, "删除记录失败,记录为空"); ALog.w(TAG, "记录为空");
} else { } else {
// 删除分块文件 // 删除分块文件
if (record.isBlock) { if (record.isBlock) {
@ -991,11 +1090,13 @@ public class CommonUtil {
/** /**
* 创建文件 当文件不存在的时候就创建一个文件 如果文件存在先删除原文件然后重新创建一个新文件 * 创建文件 当文件不存在的时候就创建一个文件 如果文件存在先删除原文件然后重新创建一个新文件
*
* @return {@code true} 创建成功{@code false} 创建失败
*/ */
public static void createFile(String path) { public static boolean createFile(String path) {
if (TextUtils.isEmpty(path)) { if (TextUtils.isEmpty(path)) {
ALog.e(TAG, "文件路径不能为null"); ALog.e(TAG, "文件路径不能为null");
return; return false;
} }
File file = new File(path); File file = new File(path);
if (file.getParentFile() == null || !file.getParentFile().exists()) { if (file.getParentFile() == null || !file.getParentFile().exists()) {
@ -1016,10 +1117,13 @@ public class CommonUtil {
try { try {
if (file.createNewFile()) { if (file.createNewFile()) {
ALog.d(TAG, "创建文件成功:" + file.getAbsolutePath()); ALog.d(TAG, "创建文件成功:" + file.getAbsolutePath());
return true;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return false;
} }
/** /**

@ -19,6 +19,7 @@
- 初始化时自动判断文件是否被删除,文件被删除的任务将自动重置默认值 - 初始化时自动判断文件是否被删除,文件被删除的任务将自动重置默认值
- 修复刷新url后,文件无法删除的 bug - 修复刷新url后,文件无法删除的 bug
- fix bug https://github.com/AriaLyy/Aria/issues/309 - fix bug https://github.com/AriaLyy/Aria/issues/309
- 优化配置文件的读取
+ v_3.5.1 + v_3.5.1
- 优化`taskExists`方法 - 优化`taskExists`方法
- 添加`post`参数请求支持 - 添加`post`参数请求支持

@ -13,7 +13,7 @@
<download> <download>
<!--设置任务最大下载速度,0表示不限速,单位为:kb--> <!--设置任务最大下载速度,0表示不限速,单位为:kb-->
<maxSpeed value="0"/> <maxSpeed value="128"/>
<!-- <!--
多线程下载是否使用块下载模式,{@code true}使用,{@code false}不使用 多线程下载是否使用块下载模式,{@code true}使用,{@code false}不使用

@ -47,11 +47,11 @@ import java.util.Map;
public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> { public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
private static final String DOWNLOAD_URL = private String DOWNLOAD_URL =
//"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.apks"; //"http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apks";
"http://120.55.95.61:8811/ghcg/zg/武义总规纲要成果.zip"; "http://120.55.95.61:8811/ghcg/zg/武义总规纲要成果.zips";
//"https://yizi-kejian.oss-cn-beijing.aliyuncs.com/qimeng/package1/qmtable11.zip"; //"https://yizi-kejian.oss-cn-beijing.aliyuncs.com/qimeng/package1/qmtable11.zip";
//"http://rs.0.gaoshouyou.com/d/04/1e/400423a7551e1f3f0eb1812afa1f9b44.apk"; //"http://rs.0.gaoshouyou.com/d/04/1e/400423a7551e1f3f0eb1812afa1f9b44.apk";
//"http://58.210.9.131/tpk/sipgt//TDLYZTGH.tpk"; //chunked 下载 //"http://58.210.9.131/tpk/sipgt//TDLYZTGH.tpk"; //chunked 下载
@ -77,8 +77,8 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
* 设置start stop 按钮状态 * 设置start stop 按钮状态
*/ */
private void setBtState(boolean state) { private void setBtState(boolean state) {
mStart.setEnabled(state); //mStart.setEnabled(state);
mStop.setEnabled(!state); //mStop.setEnabled(!state);
} }
@Override public boolean onCreateOptionsMenu(Menu menu) { @Override public boolean onCreateOptionsMenu(Menu menu) {
@ -141,7 +141,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
@Download.onTaskRunning protected void running(DownloadTask task) { @Download.onTaskRunning protected void running(DownloadTask task) {
ALog.d(TAG, String.format("%s_running_%s", getClass().getName(), hashCode())); ALog.d(TAG, String.format("%s_running_%s", getClass().getName(), hashCode()));
if (task.getKey().equals(DOWNLOAD_URL)) { //if (task.getKey().equals(DOWNLOAD_URL)) {
//Log.d(TAG, task.getKey()); //Log.d(TAG, task.getKey());
long len = task.getFileSize(); long len = task.getFileSize();
if (len == 0) { if (len == 0) {
@ -150,7 +150,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
getBinding().setProgress(task.getPercent()); getBinding().setProgress(task.getPercent());
} }
getBinding().setSpeed(task.getConvertSpeed()); getBinding().setSpeed(task.getConvertSpeed());
} //}
} }
@Download.onTaskResume void taskResume(DownloadTask task) { @Download.onTaskResume void taskResume(DownloadTask task) {
@ -187,16 +187,17 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
.load(DOWNLOAD_URL) .load(DOWNLOAD_URL)
.updateUrl("http://120.55.95.61:8811/ghcg/zg/武义总规纲要成果.zip") .updateUrl("http://120.55.95.61:8811/ghcg/zg/武义总规纲要成果.zip")
.start(); .start();
//DOWNLOAD_URL = "http://120.55.95.61:8811/ghcg/zg/武义总规纲要成果.zip";
//ALog.d(TAG, ALog.getExceptionString(e)); //ALog.d(TAG, ALog.getExceptionString(e));
} }
} }
@Download.onTaskComplete void taskComplete(DownloadTask task) { @Download.onTaskComplete void taskComplete(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) { //if (task.getKey().equals(DOWNLOAD_URL)) {
getBinding().setProgress(100); getBinding().setProgress(100);
Toast.makeText(SingleTaskActivity.this, "下载完成", Toast.LENGTH_SHORT).show(); Toast.makeText(SingleTaskActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
mStart.setText("重新开始?"); mStart.setText("重新开始?");
mCancel.setEnabled(false); //mCancel.setEnabled(false);
setBtState(true); setBtState(true);
getBinding().setSpeed(""); getBinding().setSpeed("");
L.d(TAG, "path ==> " + task.getDownloadEntity().getDownloadPath()); L.d(TAG, "path ==> " + task.getDownloadEntity().getDownloadPath());
@ -207,7 +208,7 @@ public class SingleTaskActivity extends BaseActivity<ActivitySingleBinding> {
//File apkFile = new File(task.getDownloadPath()); //File apkFile = new File(task.getDownloadPath());
//install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); //install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//startActivity(install); //startActivity(install);
} //}
} }
@Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) { @Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) {

@ -96,7 +96,7 @@ public class HttpUploadActivity extends BaseActivity<ActivityUploadBinding> {
@Upload.onTaskComplete public void taskComplete(UploadTask task) { @Upload.onTaskComplete public void taskComplete(UploadTask task) {
L.d(TAG, "上传完成"); L.d(TAG, "上传完成");
L.d(TAG, "上传成功返回数据(如果有的话):" + task.getEntity().getResponseStr()); L.d(TAG, "上传成功服务端返回数据(如果有的话):" + task.getEntity().getResponseStr());
getBinding().setSpeed(""); getBinding().setSpeed("");
getBinding().setProgress(100); getBinding().setProgress(100);
} }

@ -23,28 +23,90 @@ import com.arialyy.aria.core.queue.UploadTaskQueue;
import com.arialyy.aria.util.ALog; import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.AriaCrashHandler; import com.arialyy.aria.util.AriaCrashHandler;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.ErrorHelp;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.io.Serializable;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Properties;
/** /**
* Created by lyy on 2016/12/8. * Created by lyy on 2016/12/8. 信息配置
* 信息配置
*/ */
public class Configuration { final class Configuration {
static final String TAG = "Configuration"; private static final String TAG = "Configuration";
static final String DOWNLOAD_CONFIG_FILE = "/Aria/DownloadConfig.properties"; private static final String DOWNLOAD_CONFIG_FILE = "/Aria/AriaDownload.cfg";
static final String UPLOAD_CONFIG_FILE = "/Aria/UploadConfig.properties"; private static final String UPLOAD_CONFIG_FILE = "/Aria/AriaUpload.cfg";
static final String APP_CONFIG_FILE = "/Aria/AppConfig.properties"; private static final String APP_CONFIG_FILE = "/Aria/AriaApp.cfg";
private static final int TYPE_DOWNLOAD = 1;
private static final int TYPE_UPLOAD = 2;
private static final int TYPE_APP = 3;
private static volatile Configuration INSTANCE = null;
static final String XML_FILE = "/Aria/aria_config.xml"; static final String XML_FILE = "/Aria/aria_config.xml";
static final int TYPE_DOWNLOAD = 1; DownloadConfig downloadCfg;
static final int TYPE_UPLOAD = 2; UploadConfig uploadCfg;
static final int TYPE_APP = 3; AppConfig appCfg;
private Configuration() {
//删除老版本的配置文件
String basePath = AriaManager.APP.getFilesDir().getPath();
File oldDCfg = new File(String.format("%s/Aria/DownloadConfig.properties", basePath));
if (oldDCfg.exists()) { // 只需要判断一个
File oldUCfg = new File(String.format("%s/Aria/UploadConfig.properties", basePath));
File oldACfg = new File(String.format("%s/Aria/AppConfig.properties", basePath));
oldDCfg.delete();
oldUCfg.delete();
oldACfg.delete();
// 删除配置触发更新
File temp = new File(String.format("%s%s", basePath, XML_FILE));
if (temp.exists()) {
temp.delete();
}
}
File newDCfg = new File(String.format("%s%s", basePath, DOWNLOAD_CONFIG_FILE));
File newUCfg = new File(String.format("%s%s", basePath, UPLOAD_CONFIG_FILE));
File newACfg = new File(String.format("%s%s", basePath, APP_CONFIG_FILE));
// 加载下载配置
if (newDCfg.exists()) {
downloadCfg = (DownloadConfig) CommonUtil.readObjFromFile(newDCfg.getPath());
}
if (downloadCfg == null) {
downloadCfg = new DownloadConfig();
}
// 加载上传配置
if (newUCfg.exists()) {
uploadCfg = (UploadConfig) CommonUtil.readObjFromFile(newUCfg.getPath());
}
if (uploadCfg == null) {
uploadCfg = new UploadConfig();
}
// 加载app配置
if (newACfg.exists()) {
appCfg = (AppConfig) CommonUtil.readObjFromFile(newACfg.getPath());
}
if (appCfg == null) {
appCfg = new AppConfig();
}
}
static Configuration getInstance() {
if (INSTANCE == null) {
synchronized (AppConfig.class) {
INSTANCE = new Configuration();
}
}
return INSTANCE;
}
abstract static class BaseConfig { /**
* 检查配置文件是否存在只要{@link DownloadConfig}{@link UploadConfig}{@link AppConfig}其中一个不存在 则任务配置文件不存在
*
* @return {@code true}配置存在{@code false}配置不存在
*/
boolean configExists() {
String basePath = AriaManager.APP.getFilesDir().getPath();
return (new File(String.format("%s%s", basePath, DOWNLOAD_CONFIG_FILE))).exists()
&& (new File(String.format("%s%s", basePath, UPLOAD_CONFIG_FILE))).exists()
&& (new File(String.format("%s%s", basePath, APP_CONFIG_FILE))).exists();
}
abstract static class BaseConfig implements Serializable {
/** /**
* 类型 * 类型
@ -54,83 +116,10 @@ public class Configuration {
abstract int getType(); abstract int getType();
/** /**
* 加载配置 * 保存配置
*/
void loadConfig() {
String path = null;
Class clazz = null;
switch (getType()) {
case TYPE_DOWNLOAD:
path = DOWNLOAD_CONFIG_FILE;
clazz = DownloadConfig.class;
break;
case TYPE_UPLOAD:
path = UPLOAD_CONFIG_FILE;
clazz = UploadConfig.class;
break;
case TYPE_APP:
path = APP_CONFIG_FILE;
clazz = AppConfig.class;
break;
}
if (TextUtils.isEmpty(path)) {
ALog.e(TAG, "读取配置失败:未知文件类型");
ErrorHelp.saveError(TAG, "读取配置失败:未知文件类型", "");
return;
}
File file = new File(AriaManager.APP.getFilesDir().getPath() + path);
if (file.exists()) {
Properties properties = CommonUtil.loadConfig(file);
List<Field> fields = CommonUtil.getAllFields(clazz);
try {
for (Field field : fields) {
int m = field.getModifiers();
String fileName = field.getName();
if (fileName.equals("oldMaxTaskNum")
|| field.isSynthetic()
|| Modifier.isFinal(m)
|| Modifier.isStatic(m)
|| fileName.equals("shadow$_klass_")
|| fileName.equals("shadow$_monitor_")) {
continue;
}
field.setAccessible(true);
String value = properties.getProperty(field.getName());
if (TextUtils.isEmpty(value) || value.equalsIgnoreCase("null")) continue;
Class<?> type = field.getType();
if (type == String.class) {
field.set(this, value);
} else if (type == int.class || type == Integer.class) {
if (fileName.equalsIgnoreCase("maxSpeed")) { //兼容以前版本,以前maxSpeed是double类型的
Double d = Double.parseDouble(value);
field.setInt(this, (int) d.doubleValue());
} else {
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) {
if (TextUtils.isEmpty(value)) {
value = "0";
}
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();
}
}
}
/**
* 保存key
*/ */
void saveKey(String key, String value) { void save() {
String basePath = AriaManager.APP.getFilesDir().getPath();
String path = null; String path = null;
switch (getType()) { switch (getType()) {
case TYPE_DOWNLOAD: case TYPE_DOWNLOAD:
@ -143,48 +132,12 @@ public class Configuration {
path = APP_CONFIG_FILE; path = APP_CONFIG_FILE;
break; break;
} }
File file = new File( if (!TextUtils.isEmpty(path)) {
AriaManager.APP.getFilesDir().getPath() + path); String tempPath = String.format("%s%s", basePath, path);
if (file.exists()) { CommonUtil.deleteFile(tempPath);
Properties properties = CommonUtil.loadConfig(file); CommonUtil.writeObjToFile(tempPath, this);
properties.setProperty(key, value); } else {
CommonUtil.saveConfig(file, properties); ALog.e(TAG, String.format("保存配置失败,配置类型:%s,原因:路径错误", getType()));
}
}
/**
* 保存配置
*/
void saveAll() {
List<Field> fields = CommonUtil.getAllFields(getClass());
try {
String path = null;
switch (getType()) {
case TYPE_DOWNLOAD:
path = DOWNLOAD_CONFIG_FILE;
break;
case TYPE_UPLOAD:
path = UPLOAD_CONFIG_FILE;
break;
case TYPE_APP:
path = APP_CONFIG_FILE;
break;
}
File file = new File(
AriaManager.APP.getFilesDir().getPath() + path);
Properties properties = CommonUtil.loadConfig(file);
for (Field field : fields) {
int m = field.getModifiers();
if (field.isSynthetic() || Modifier.isFinal(m) || Modifier.isStatic(m) || field.getName()
.equals("shadow$_klass_") || field.getName().equals("shadow$_monitor_")) {
continue;
}
field.setAccessible(true);
properties.setProperty(field.getName(), field.get(this) + "");
}
CommonUtil.saveConfig(file, properties);
} catch (IllegalAccessException e) {
e.printStackTrace();
} }
} }
} }
@ -192,7 +145,7 @@ public class Configuration {
/** /**
* 通用任务配置 * 通用任务配置
*/ */
abstract static class BaseTaskConfig extends BaseConfig { abstract static class BaseTaskConfig extends BaseConfig implements Serializable {
/** /**
* 设置写文件buff大小该数值大小不能小于2048数值变小下载速度会变慢 * 设置写文件buff大小该数值大小不能小于2048数值变小下载速度会变慢
@ -259,7 +212,7 @@ public class Configuration {
public BaseTaskConfig setMaxSpeed(int maxSpeed) { public BaseTaskConfig setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed; this.maxSpeed = maxSpeed;
saveKey("maxSpeed", String.valueOf(maxSpeed)); save();
return this; return this;
} }
@ -278,7 +231,7 @@ public class Configuration {
return this; return this;
} }
this.updateInterval = updateInterval; this.updateInterval = updateInterval;
saveKey("updateInterval", String.valueOf(updateInterval)); save();
return this; return this;
} }
@ -288,7 +241,7 @@ public class Configuration {
public BaseTaskConfig setQueueMod(String queueMod) { public BaseTaskConfig setQueueMod(String queueMod) {
this.queueMod = queueMod; this.queueMod = queueMod;
saveKey("queueMod", queueMod); save();
return this; return this;
} }
@ -302,7 +255,7 @@ public class Configuration {
public BaseTaskConfig setReTryNum(int reTryNum) { public BaseTaskConfig setReTryNum(int reTryNum) {
this.reTryNum = reTryNum; this.reTryNum = reTryNum;
saveKey("reTryNum", String.valueOf(reTryNum)); save();
return this; return this;
} }
@ -312,7 +265,7 @@ public class Configuration {
public BaseTaskConfig setReTryInterval(int reTryInterval) { public BaseTaskConfig setReTryInterval(int reTryInterval) {
this.reTryInterval = reTryInterval; this.reTryInterval = reTryInterval;
saveKey("reTryInterval", String.valueOf(reTryInterval)); save();
return this; return this;
} }
@ -322,7 +275,7 @@ public class Configuration {
public BaseTaskConfig setConvertSpeed(boolean convertSpeed) { public BaseTaskConfig setConvertSpeed(boolean convertSpeed) {
isConvertSpeed = convertSpeed; isConvertSpeed = convertSpeed;
saveKey("isConvertSpeed", String.valueOf(isConvertSpeed)); save();
return this; return this;
} }
@ -332,7 +285,7 @@ public class Configuration {
public BaseTaskConfig setConnectTimeOut(int connectTimeOut) { public BaseTaskConfig setConnectTimeOut(int connectTimeOut) {
this.connectTimeOut = connectTimeOut; this.connectTimeOut = connectTimeOut;
saveKey("connectTimeOut", String.valueOf(connectTimeOut)); save();
return this; return this;
} }
@ -342,7 +295,7 @@ public class Configuration {
public BaseTaskConfig setNotNetRetry(boolean notNetRetry) { public BaseTaskConfig setNotNetRetry(boolean notNetRetry) {
this.notNetRetry = notNetRetry; this.notNetRetry = notNetRetry;
saveKey("notNetRetry", String.valueOf(notNetRetry)); save();
return this; return this;
} }
@ -352,7 +305,7 @@ public class Configuration {
public BaseTaskConfig setIOTimeOut(int iOTimeOut) { public BaseTaskConfig setIOTimeOut(int iOTimeOut) {
this.iOTimeOut = iOTimeOut; this.iOTimeOut = iOTimeOut;
saveKey("iOTimeOut", String.valueOf(iOTimeOut)); save();
return this; return this;
} }
@ -362,7 +315,7 @@ public class Configuration {
public BaseTaskConfig setBuffSize(int buffSize) { public BaseTaskConfig setBuffSize(int buffSize) {
this.buffSize = buffSize; this.buffSize = buffSize;
saveKey("buffSize", String.valueOf(buffSize)); save();
return this; return this;
} }
} }
@ -370,7 +323,7 @@ public class Configuration {
/** /**
* 下载配置 * 下载配置
*/ */
public static class DownloadConfig extends BaseTaskConfig { public static class DownloadConfig extends BaseTaskConfig implements Serializable {
/** /**
* 设置https ca 证书信息path 为assets目录下的CA证书完整路径 * 设置https ca 证书信息path 为assets目录下的CA证书完整路径
@ -381,22 +334,14 @@ public class Configuration {
*/ */
String caName; String caName;
/** /**
* 下载线程数下载线程数不能小于1 * 下载线程数下载线程数不能小于1 注意 1线程下载数改变后新的下载任务才会生效 2如果任务大小小于1m该设置不会生效
* 注意 * 3从3.4.1开始如果线程数为1文件初始化时将不再预占用对应长度的空间下载多少byte则占多大的空间 对于采用多线程的任务或旧任务依然采用原来的文件空间占用方式
* 1线程下载数改变后新的下载任务才会生效
* 2如果任务大小小于1m该设置不会生效
* 3从3.4.1开始如果线程数为1文件初始化时将不再预占用对应长度的空间下载多少byte则占多大的空间
* 对于采用多线程的任务或旧任务依然采用原来的文件空间占用方式
*/ */
int threadNum = 3; int threadNum = 3;
/** /**
* 多线程下载是否使用块下载模式{@code true}使用{@code false}不使用 * 多线程下载是否使用块下载模式{@code true}使用{@code false}不使用 注意 1使用分块模式在读写性能底下的手机上合并文件需要的时间会更加长
* 注意 * 2优点是使用多线程的块下载初始化时文件初始化时将不会预占用对应长度的空间 3只对新的多线程下载任务有效 4只对多线程的任务有效
* 1使用分块模式在读写性能底下的手机上合并文件需要的时间会更加长
* 2优点是使用多线程的块下载初始化时文件初始化时将不会预占用对应长度的空间
* 3只对新的多线程下载任务有效
* 4只对多线程的任务有效
*/ */
boolean useBlock = false; boolean useBlock = false;
@ -413,21 +358,21 @@ public class Configuration {
public DownloadConfig setUseBlock(boolean useBlock) { public DownloadConfig setUseBlock(boolean useBlock) {
this.useBlock = useBlock; this.useBlock = useBlock;
saveKey("useBlock", String.valueOf(useBlock)); save();
return this; return this;
} }
public DownloadConfig setMaxTaskNum(int maxTaskNum) { public DownloadConfig setMaxTaskNum(int maxTaskNum) {
oldMaxTaskNum = this.maxTaskNum; oldMaxTaskNum = this.maxTaskNum;
this.maxTaskNum = maxTaskNum; this.maxTaskNum = maxTaskNum;
saveKey("maxTaskNum", String.valueOf(maxTaskNum));
DownloadTaskQueue.getInstance().setMaxTaskNum(maxTaskNum); DownloadTaskQueue.getInstance().setMaxTaskNum(maxTaskNum);
save();
return this; return this;
} }
public DownloadConfig setThreadNum(int threadNum) { public DownloadConfig setThreadNum(int threadNum) {
this.threadNum = threadNum; this.threadNum = threadNum;
saveKey("threadNum", String.valueOf(threadNum)); save();
return this; return this;
} }
@ -437,7 +382,7 @@ public class Configuration {
public DownloadConfig setCaPath(String caPath) { public DownloadConfig setCaPath(String caPath) {
this.caPath = caPath; this.caPath = caPath;
saveKey("caPath", caPath); save();
return this; return this;
} }
@ -447,7 +392,7 @@ public class Configuration {
public DownloadConfig setCaName(String caName) { public DownloadConfig setCaName(String caName) {
this.caName = caName; this.caName = caName;
saveKey("caName", caName); save();
return this; return this;
} }
@ -456,18 +401,6 @@ public class Configuration {
} }
private DownloadConfig() { private DownloadConfig() {
loadConfig();
}
private static DownloadConfig INSTANCE = null;
static DownloadConfig getInstance() {
if (INSTANCE == null) {
synchronized (DownloadConfig.class) {
INSTANCE = new DownloadConfig();
}
}
return INSTANCE;
} }
@Override int getType() { @Override int getType() {
@ -478,11 +411,11 @@ public class Configuration {
/** /**
* 上传配置 * 上传配置
*/ */
public static class UploadConfig extends BaseTaskConfig { public static class UploadConfig extends BaseTaskConfig implements Serializable {
private static UploadConfig INSTANCE = null; private static UploadConfig INSTANCE = null;
private UploadConfig() { private UploadConfig() {
loadConfig(); //loadConfig();
} }
@Override public UploadConfig setMaxSpeed(int maxSpeed) { @Override public UploadConfig setMaxSpeed(int maxSpeed) {
@ -494,8 +427,8 @@ public class Configuration {
public UploadConfig setMaxTaskNum(int maxTaskNum) { public UploadConfig setMaxTaskNum(int maxTaskNum) {
oldMaxTaskNum = this.maxTaskNum; oldMaxTaskNum = this.maxTaskNum;
this.maxTaskNum = maxTaskNum; this.maxTaskNum = maxTaskNum;
saveKey("maxTaskNum", String.valueOf(maxTaskNum));
UploadTaskQueue.getInstance().setMaxTaskNum(maxTaskNum); UploadTaskQueue.getInstance().setMaxTaskNum(maxTaskNum);
save();
return this; return this;
} }
@ -517,10 +450,8 @@ public class Configuration {
* 应用配置 * 应用配置
*/ */
public static class AppConfig extends BaseConfig { public static class AppConfig extends BaseConfig {
private static AppConfig INSTANCE = null;
/** /**
* 是否使用{@link AriaCrashHandler}来捕获异常 * 是否使用{@link AriaCrashHandler}来捕获异常 {@code true} 使用{@code false} 不使用
* {@code true} 使用{@code false} 不使用
*/ */
boolean useAriaCrashHandler; boolean useAriaCrashHandler;
@ -531,23 +462,13 @@ public class Configuration {
*/ */
int logLevel; int logLevel;
AppConfig() { private AppConfig() {
loadConfig();
}
static AppConfig getInstance() {
if (INSTANCE == null) {
synchronized (AppConfig.class) {
INSTANCE = new AppConfig();
}
}
return INSTANCE;
} }
public AppConfig setLogLevel(int level) { public AppConfig setLogLevel(int level) {
this.logLevel = level; this.logLevel = level;
ALog.LOG_LEVEL = level; ALog.LOG_LEVEL = level;
saveKey("logLevel", String.valueOf(logLevel)); save();
return this; return this;
} }
@ -561,12 +482,12 @@ public class Configuration {
public AppConfig setUseAriaCrashHandler(boolean useAriaCrashHandler) { public AppConfig setUseAriaCrashHandler(boolean useAriaCrashHandler) {
this.useAriaCrashHandler = useAriaCrashHandler; this.useAriaCrashHandler = useAriaCrashHandler;
saveKey("useAriaCrashHandler", String.valueOf(useAriaCrashHandler));
if (useAriaCrashHandler) { if (useAriaCrashHandler) {
Thread.setDefaultUncaughtExceptionHandler(new AriaCrashHandler()); Thread.setDefaultUncaughtExceptionHandler(new AriaCrashHandler());
} else { } else {
Thread.setDefaultUncaughtExceptionHandler(null); Thread.setDefaultUncaughtExceptionHandler(null);
} }
save();
return this; return this;
} }

Loading…
Cancel
Save