pull/2/head
lyy 9 years ago
parent e586168e30
commit e4e80048e7
  1. 8
      .idea/gradle.xml
  2. 2
      .idea/misc.xml
  3. 1
      .idea/modules.xml
  4. 9
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadCommand.java
  5. 52
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadManager.java
  6. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadTarget.java
  7. 5
      downloadutil/src/main/java/com/arialyy/downloadutil/core/TaskFactory.java
  8. 1
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/AddCommand.java
  9. 14
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/CancelCommand.java
  10. 185
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/CommandFactory.java
  11. 15
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/IDownloadCommand.java
  12. 3
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StartCommand.java
  13. 22
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StateCommand.java
  14. 22
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StopCommand.java
  15. 9
      downloadutil/src/main/java/com/arialyy/downloadutil/core/inf/ITask.java
  16. 6
      downloadutil/src/main/java/com/arialyy/downloadutil/core/pool/CachePool.java
  17. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/pool/ExecutePool.java
  18. 66
      downloadutil/src/main/java/com/arialyy/downloadutil/help/CheckHelp.java
  19. 37
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/DbUtil.java
  20. 73
      downloadutil/src/main/java/com/arialyy/downloadutil/util/DownLoadUtil.java

@ -13,7 +13,13 @@
<option value="$PROJECT_DIR$/downloadutil" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
<option name="myModules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/downloadutil" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>

@ -53,7 +53,7 @@
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">

@ -3,7 +3,6 @@
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/DownloadDemo.iml" filepath="$PROJECT_DIR$/DownloadDemo.iml" />
<module fileurl="file://$PROJECT_DIR$/DownloadUtil.iml" filepath="$PROJECT_DIR$/DownloadUtil.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/downloadutil/downloadutil.iml" filepath="$PROJECT_DIR$/downloadutil/downloadutil.iml" />
</modules>

@ -1,9 +0,0 @@
package com.arialyy.downloadutil.core;
/**
* Created by lyy on 2016/8/14.
* 命令抽象类
*/
public abstract class DownloadCommand {
}

@ -2,15 +2,22 @@ package com.arialyy.downloadutil.core;
import android.content.Context;
import com.arialyy.downloadutil.core.command.IDownloadCommand;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lyy on 2016/8/11.
* 下载管理器通过命令的方式控制下载
*/
public class DownloadManager {
private static final Object LOCK = new Object();
private static volatile DownloadManager INSTANCE = null;
/**
* 下载开始前事件
*/
public static final String ACTION_PRE = "ACTION_PRE";
public static final String ACTION_PRE = "ACTION_PRE";
/**
* 开始下载事件
@ -57,6 +64,12 @@ public class DownloadManager {
*/
public static final String CURRENT_LOCATION = "CURRENT_LOCATION";
private List<IDownloadCommand> mCommands = new ArrayList<>();
private DownloadManager() {
}
private Context mContext;
private DownloadManager(Context context) {
@ -64,7 +77,42 @@ public class DownloadManager {
}
public static DownloadManager getInstance(Context context) {
return new DownloadManager(context);
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new DownloadManager(context.getApplicationContext());
}
}
return INSTANCE;
}
/**
* 设置命令
*
* @param command
*/
public void setCommant(IDownloadCommand command) {
mCommands.add(command);
}
/**
* 设置一组命令
*
* @param commands
*/
public void setCommands(List<IDownloadCommand> commands) {
if (commands != null && commands.size() > 0) {
mCommands.addAll(commands);
}
}
/**
* 执行所有设置的命令
*/
public synchronized void exe() {
for (IDownloadCommand command : mCommands) {
command.executeComment();
}
mCommands.clear();
}
}

@ -77,7 +77,7 @@ public class DownloadTarget extends IDownloadTarget {
if (task == null) {
task = mCachePool.getTask(entity.getDownloadUrl());
}
if (task == null){
if (task == null) {
task = createTask(entity);
}
return task;

@ -30,9 +30,10 @@ public class TaskFactory {
/**
* 创建普通下载任务
*
* @param context
* @param entity 下载实体
* @param handler {@link com.arialyy.downloadutil.core.IDownloadTarget.AutoTaskHandler}
* @param entity 下载实体
* @param handler {@link com.arialyy.downloadutil.core.IDownloadTarget.AutoTaskHandler}
* @return
*/
public Task createTask(Context context, DownloadEntity entity, Handler handler) {

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -9,11 +10,12 @@ import com.arialyy.downloadutil.entity.DownloadEntity;
*/
class CancelCommand extends IDownloadCommand {
CancelCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
CancelCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
@Override public void executeComment() {
target.cancelTask(target.getTask(mEntity));
}
@Override
public void executeComment() {
target.cancelTask(target.getTask(mEntity));
}
}

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -8,108 +9,108 @@ import com.arialyy.downloadutil.entity.DownloadEntity;
* 命令工厂
*/
public class CommandFactory {
/**
* 创建任务
*/
public static final int TASK_CREATE = 0x122;
/**
* 启动任务
*/
public static final int TASK_START = 0x123;
/**
* 取消任务
*/
public static final int TASK_CANCEL = 0x124;
/**
* 停止任务
*/
public static final int TASK_STOP = 0x125;
/**
* 获取任务状态
*/
public static final int TASK_STATE = 0x126;
/**
* 创建任务
*/
public static final int TASK_CREATE = 0x122;
/**
* 启动任务
*/
public static final int TASK_START = 0x123;
/**
* 取消任务
*/
public static final int TASK_CANCEL = 0x124;
/**
* 停止任务
*/
public static final int TASK_STOP = 0x125;
/**
* 获取任务状态
*/
public static final int TASK_STATE = 0x126;
private static final Object LOCK = new Object();
private static volatile CommandFactory INSTANCE = null;
private static final Object LOCK = new Object();
private static volatile CommandFactory INSTANCE = null;
private CommandFactory() {
private CommandFactory() {
}
}
public static CommandFactory getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new CommandFactory();
}
public static CommandFactory getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new CommandFactory();
}
}
return INSTANCE;
}
return INSTANCE;
}
/**
* @param context context
* @param entity 下载实体
* @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link
* #TASK_STOP}{@link #TASK_STATE}
*/
public IDownloadCommand createCommand(Context context, DownloadEntity entity, int type) {
switch (type) {
case TASK_CREATE:
return createAddCommand(context, entity);
case TASK_START:
return createStartCommand(context, entity);
case TASK_CANCEL:
return createCancelCommand(context, entity);
case TASK_STOP:
return createStopCommand(context, entity);
case TASK_STATE:
return createStateCommand(context, entity);
default:
return null;
/**
* @param context context
* @param entity 下载实体
* @param type 命令类型{@link #TASK_CREATE}{@link #TASK_START}{@link #TASK_CANCEL}{@link
* #TASK_STOP}{@link #TASK_STATE}
*/
public IDownloadCommand createCommand(Context context, DownloadEntity entity, int type) {
switch (type) {
case TASK_CREATE:
return createAddCommand(context, entity);
case TASK_START:
return createStartCommand(context, entity);
case TASK_CANCEL:
return createCancelCommand(context, entity);
case TASK_STOP:
return createStopCommand(context, entity);
case TASK_STATE:
return createStateCommand(context, entity);
default:
return null;
}
}
}
/**
* 创建获取任务状态的命令
*
* @return {@link StateCommand}
*/
private StateCommand createStateCommand(Context context, DownloadEntity entity) {
return new StateCommand(context, entity);
}
/**
* 创建获取任务状态的命令
*
* @return {@link StateCommand}
*/
private StateCommand createStateCommand(Context context, DownloadEntity entity) {
return new StateCommand(context, entity);
}
/**
* 创建停止命令
*
* @return {@link StopCommand}
*/
private StopCommand createStopCommand(Context context, DownloadEntity entity) {
return new StopCommand(context, entity);
}
/**
* 创建停止命令
*
* @return {@link StopCommand}
*/
private StopCommand createStopCommand(Context context, DownloadEntity entity) {
return new StopCommand(context, entity);
}
/**
* 创建下载任务命令
*
* @return {@link AddCommand}
*/
private AddCommand createAddCommand(Context context, DownloadEntity entity) {
return new AddCommand(context, entity);
}
/**
* 创建下载任务命令
*
* @return {@link AddCommand}
*/
private AddCommand createAddCommand(Context context, DownloadEntity entity) {
return new AddCommand(context, entity);
}
/**
* 创建启动下载命令
*
* @return {@link StartCommand}
*/
private StartCommand createStartCommand(Context context, DownloadEntity entity) {
return new StartCommand(context, entity);
}
/**
* 创建启动下载命令
*
* @return {@link StartCommand}
*/
private StartCommand createStartCommand(Context context, DownloadEntity entity) {
return new StartCommand(context, entity);
}
/**
* 创建 取消下载的命令
*
* @return {@link CancelCommand}
*/
private CancelCommand createCancelCommand(Context context, DownloadEntity entity) {
return new CancelCommand(context, entity);
}
/**
* 创建 取消下载的命令
*
* @return {@link CancelCommand}
*/
private CancelCommand createCancelCommand(Context context, DownloadEntity entity) {
return new CancelCommand(context, entity);
}
}

@ -8,6 +8,7 @@ import com.arialyy.downloadutil.core.IDownloadTarget;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.help.CheckHelp;
import java.util.List;
/**
@ -16,15 +17,15 @@ import java.util.List;
*/
public abstract class IDownloadCommand {
protected IDownloadTarget target;
protected Context mContext;
protected DownloadEntity mEntity;
protected Context mContext;
protected DownloadEntity mEntity;
/**
* @param context context
* @param entity 下载实体
* @param context context
* @param entity 下载实体
*/
protected IDownloadCommand(Context context, DownloadEntity entity){
if (!CheckHelp.checkDownloadEntity(entity)){
protected IDownloadCommand(Context context, DownloadEntity entity) {
if (!CheckHelp.checkDownloadEntity(entity)) {
return;
}
target = DownloadTarget.getInstance(context);
@ -32,7 +33,7 @@ public abstract class IDownloadCommand {
mEntity = entity;
}
public Context getContext(){
public Context getContext() {
return mContext;
}

@ -1,13 +1,14 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
* Created by lyy on 2016/8/22.
* 开始命令
*/
class StartCommand extends IDownloadCommand{
class StartCommand extends IDownloadCommand {
StartCommand(Context context, DownloadEntity entity) {
super(context, entity);

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -9,15 +10,16 @@ import com.arialyy.downloadutil.entity.DownloadEntity;
*/
class StateCommand extends IDownloadCommand {
/**
* @param context context
* @param entity 下载实体
*/
StateCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
/**
* @param context context
* @param entity 下载实体
*/
StateCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
@Override public void executeComment() {
target.getTaskState(mEntity);
}
@Override
public void executeComment() {
target.getTaskState(mEntity);
}
}

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -9,15 +10,16 @@ import com.arialyy.downloadutil.entity.DownloadEntity;
*/
class StopCommand extends IDownloadCommand {
/**
* @param context context
* @param entity 下载实体
*/
StopCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
/**
* @param context context
* @param entity 下载实体
*/
StopCommand(Context context, DownloadEntity entity) {
super(context, entity);
}
@Override public void executeComment() {
target.stopTask(target.getTask(mEntity));
}
@Override
public void executeComment() {
target.stopTask(target.getTask(mEntity));
}
}

@ -12,7 +12,7 @@ public interface ITask {
/**
* 创建一个新的下载任务创建时只是将新任务存储到缓存池
*
* @param entity 下载实体{@link DownloadEntity}
* @param entity 下载实体{@link DownloadEntity}
* @return {@link Task}
*/
public Task createTask(DownloadEntity entity);
@ -20,7 +20,7 @@ public interface ITask {
/**
* 通过下载链接从缓存池或任务池搜索下载任务如果缓存池或任务池都没有任务则创建新任务
*
* @param entity 下载实体{@link DownloadEntity}
* @param entity 下载实体{@link DownloadEntity}
* @return {@link Task}
*/
public Task getTask(DownloadEntity entity);
@ -28,14 +28,15 @@ public interface ITask {
/**
* 通过下载链接搜索下载任务
*
* @param entity 下载实体{@link DownloadEntity}
* @param entity 下载实体{@link DownloadEntity}
* @return {@code -1 ==> 错误}{@link com.arialyy.downloadutil.entity.DownloadEntity#STATE_FAIL}
*/
public int getTaskState(DownloadEntity entity);
/**
* 通过下载链接删除任务
* @param entity 下载实体{@link DownloadEntity}
*
* @param entity 下载实体{@link DownloadEntity}
*/
public void removeTask(DownloadEntity entity);

@ -78,7 +78,7 @@ public class CachePool implements IPool {
Log.e(TAG, "请传入有效的下载链接");
return null;
}
String key = Util.keyToHashKey(downloadUrl);
String key = Util.keyToHashKey(downloadUrl);
return mCacheArray.get(key);
}
}
@ -104,8 +104,8 @@ public class CachePool implements IPool {
Log.e(TAG, "请传入有效的下载链接");
return false;
}
String key = Util.keyToHashKey(downloadUrl);
Task task = mCacheArray.get(key);
String key = Util.keyToHashKey(downloadUrl);
Task task = mCacheArray.get(key);
mCacheArray.remove(key);
return mCacheQueue.remove(task);
}

@ -119,7 +119,7 @@ public class ExecutePool implements IPool {
Log.e(TAG, "请传入有效的下载链接");
return null;
}
String key = Util.keyToHashKey(downloadUrl);
String key = Util.keyToHashKey(downloadUrl);
return mExecuteArray.get(key);
}
}

@ -4,8 +4,10 @@ import android.app.Application;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.downloadutil.R;
import com.arialyy.downloadutil.entity.DownloadEntity;
import java.io.File;
/**
@ -13,38 +15,38 @@ import java.io.File;
* 检查帮助类
*/
public class CheckHelp {
private static final String TAG = "CheckHelp";
private static final String TAG = "CheckHelp";
/**
* 检测下载实体是否合法
*
* @param entity 下载实体
* @return 合法(true)
*/
public static boolean checkDownloadEntity(DownloadEntity entity) {
if (entity == null) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_entity_null));
return false;
} else if (TextUtils.isEmpty(entity.getDownloadUrl())) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_download_url_null));
return false;
} else if (TextUtils.isEmpty(entity.getFileName())){
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
return false;
} else if (TextUtils.isEmpty(entity.getDownloadPath())){
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
return false;
}
String fileName = entity.getFileName();
if (fileName.contains(" ")){
fileName = fileName.replace(" ", "_");
}
String dPath = entity.getDownloadPath();
File file = new File(dPath);
if (file.isDirectory()){
dPath += fileName;
entity.setDownloadPath(dPath);
/**
* 检测下载实体是否合法
*
* @param entity 下载实体
* @return 合法(true)
*/
public static boolean checkDownloadEntity(DownloadEntity entity) {
if (entity == null) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_entity_null));
return false;
} else if (TextUtils.isEmpty(entity.getDownloadUrl())) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_download_url_null));
return false;
} else if (TextUtils.isEmpty(entity.getFileName())) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
return false;
} else if (TextUtils.isEmpty(entity.getDownloadPath())) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
return false;
}
String fileName = entity.getFileName();
if (fileName.contains(" ")) {
fileName = fileName.replace(" ", "_");
}
String dPath = entity.getDownloadPath();
File file = new File(dPath);
if (file.isDirectory()) {
dPath += fileName;
entity.setDownloadPath(dPath);
}
return true;
}
return true;
}
}

@ -1,4 +1,5 @@
package com.arialyy.downloadutil.orm;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
@ -13,17 +14,17 @@ import java.lang.reflect.Field;
* 数据库操作工具
*/
public class DbUtil {
private static final String TAG = "DbUtil";
private volatile static DbUtil mDbUtil = null;
private int CREATE_TABLE = 0;
private int TABLE_EXISTS = 1;
private int INSERT_DATA = 2;
private int MODIFY_DATA = 3;
private int FIND_DATA = 4;
private int FIND_ALL_DATA = 5;
private int DEL_DATA = 6;
private int ROW_ID = 7;
private static final Object LOCK = new Object();
private static final String TAG = "DbUtil";
private volatile static DbUtil mDbUtil = null;
private int CREATE_TABLE = 0;
private int TABLE_EXISTS = 1;
private int INSERT_DATA = 2;
private int MODIFY_DATA = 3;
private int FIND_DATA = 4;
private int FIND_ALL_DATA = 5;
private int DEL_DATA = 6;
private int ROW_ID = 7;
private static final Object LOCK = new Object();
private SQLiteDatabase mDb;
private DbUtil() {
@ -73,8 +74,8 @@ public class DbUtil {
* 修改某行数据
*/
protected void modifyData(DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(Util.getClassName(dbEntity)).append(" SET ");
@ -136,8 +137,8 @@ public class DbUtil {
* 插入数据
*/
protected void insertData(DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
Class<?> clazz = dbEntity.getClass();
Field[] fields = Util.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(Util.getClassName(dbEntity)).append("(");
@ -214,7 +215,7 @@ public class DbUtil {
sb.append("create table ")
.append(Util.getClassName(dbEntity))
.append("(");
int i = 0;
int i = 0;
int ignoreNum = 0;
for (Field field : fields) {
i++;
@ -322,8 +323,8 @@ public class DbUtil {
i++;
}
print(ROW_ID, sb.toString());
Cursor c = mDb.rawQuery(sb.toString(), null);
int id = c.getColumnIndex("rowid");
Cursor c = mDb.rawQuery(sb.toString(), null);
int id = c.getColumnIndex("rowid");
c.close();
return id;
}

@ -13,6 +13,7 @@ import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
/**
* Created by lyy on 2015/8/25.
* 下载工具类
@ -24,24 +25,27 @@ public class DownLoadUtil {
/**
* 线程数
*/
private static final int THREAD_NUM = 3;
private static final int THREAD_NUM = 3;
/**
* 已经完成下载任务的线程数量
*/
private int mCompleteThreadNum = 0;
private int mCompleteThreadNum = 0;
private long mCurrentLocation;
private boolean isDownloading = false;
private boolean isStop = false;
private boolean isCancel = false;
private static final int TIME_OUT = 5000; //超时时间
private boolean isDownloading = false;
private boolean isStop = false;
private boolean isCancel = false;
private static final int TIME_OUT = 5000; //超时时间
boolean isNewTask = true;
private int mCancelNum = 0;
private int mStopNum = 0;
private int mStopNum = 0;
public DownLoadUtil() {
}
public IDownloadListener getListener(){
public IDownloadListener getListener() {
return mListener;
}
/**
* 获取当前下载位置
*
@ -50,21 +54,25 @@ public class DownLoadUtil {
public long getCurrentLocation() {
return mCurrentLocation;
}
public boolean isDownloading() {
return isDownloading;
}
/**
* 取消下载
*/
public void cancelDownload() {
isCancel = true;
}
/**
* 停止下载
*/
public void stopDownload() {
isStop = true;
}
/**
* 多线程断点续传下载文件暂停和继续
*
@ -101,7 +109,7 @@ public class DownLoadUtil {
public void run() {
try {
mListener = downloadListener;
URL url = new URL(downloadUrl);
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
@ -140,16 +148,16 @@ public class DownLoadUtil {
}
}
}
int blockSize = fileLength / THREAD_NUM;
SparseArray<Thread> tasks = new SparseArray<>();
int[] recordL = new int[THREAD_NUM];
int rl = 0;
int blockSize = fileLength / THREAD_NUM;
SparseArray<Thread> tasks = new SparseArray<>();
int[] recordL = new int[THREAD_NUM];
int rl = 0;
for (int i = 0; i < THREAD_NUM; i++) {
recordL[i] = -1;
}
for (int i = 0; i < THREAD_NUM; i++) {
long startL = i * blockSize, endL = (i + 1) * blockSize;
Object state = pro.getProperty(dFile.getName() + "_state_" + i);
long startL = i * blockSize, endL = (i + 1) * blockSize;
Object state = pro.getProperty(dFile.getName() + "_state_" + i);
if (state != null && Integer.parseInt(state + "") == 1) { //该线程已经完成
mCurrentLocation += endL - startL;
Log.d(TAG, "++++++++++ 线程_" + i + "_已经下载完成 ++++++++++");
@ -176,7 +184,7 @@ public class DownLoadUtil {
startL = r;
recordL[rl] = i;
rl++;
}else {
} else {
isNewTask = true;
}
if (isNewTask) {
@ -187,7 +195,7 @@ public class DownLoadUtil {
endL = fileLength;//如果整个文件的大小不为线程个数的整数倍,则最后一个线程的结束位置即为文件的总长度
}
DownloadEntity entity = new DownloadEntity(context, fileLength, downloadUrl, dFile, i, startL, endL);
DownLoadTask task = new DownLoadTask(entity);
DownLoadTask task = new DownLoadTask(entity);
tasks.put(i, new Thread(task));
}
if (mCurrentLocation > 0) {
@ -211,30 +219,34 @@ public class DownLoadUtil {
}
}).start();
}
private void failDownload(String msg){
private void failDownload(String msg) {
Log.e(TAG, msg);
isDownloading = false;
stopDownload();
mListener.onFail();
System.gc();
}
/**
* 多线程下载任务类,不能使用AsyncTask来进行多线程下载因为AsyncTask是串行执行的这种方式下载速度太慢了
*/
private class DownLoadTask implements Runnable {
private static final String TAG = "DownLoadTask";
private DownloadEntity dEntity;
private String configFPath;
private String configFPath;
public DownLoadTask(DownloadEntity downloadInfo) {
this.dEntity = downloadInfo;
configFPath = dEntity.context.getFilesDir().getPath() + "/temp/" + dEntity.tempFile.getName() + ".properties";
}
@Override
public void run() {
long currentLocation = 0;
try {
Log.d(TAG, "线程_" + dEntity.threadId + "_正在下载【" + "开始位置 : " + dEntity.startLocation + ",结束位置:" + dEntity.endLocation + "】");
URL url = new URL(dEntity.downloadUrl);
URL url = new URL(dEntity.downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//在头里面请求下载开始位置和结束位置
conn.setRequestProperty("Range", "bytes=" + dEntity.startLocation + "-" + dEntity.endLocation);
@ -250,7 +262,7 @@ public class DownLoadUtil {
//设置每条线程写入文件的位置
file.seek(dEntity.startLocation);
byte[] buffer = new byte[1024];
int len;
int len;
//当前子线程的下载位置
currentLocation = dEntity.startLocation;
while ((len = is.read(buffer)) != -1) {
@ -353,30 +365,33 @@ public class DownLoadUtil {
}
}
}
/**
* 将记录写入到配置文件
*
* @param record
*/
private void writeConfig(String key, String record) throws IOException {
File configFile = new File(configFPath);
Properties pro = Util.loadConfig(configFile);
File configFile = new File(configFPath);
Properties pro = Util.loadConfig(configFile);
pro.setProperty(key, record);
Util.saveConfig(configFile, pro);
}
}
/**
* 子线程下载信息类
*/
private class DownloadEntity {
//文件大小
long fileSize;
String downloadUrl;
int threadId;
long startLocation;
long endLocation;
File tempFile;
long fileSize;
String downloadUrl;
int threadId;
long startLocation;
long endLocation;
File tempFile;
Context context;
public DownloadEntity(Context context, long fileSize, String downloadUrl, File file, int threadId, long startLocation, long endLocation) {
this.fileSize = fileSize;
this.downloadUrl = downloadUrl;

Loading…
Cancel
Save