没做啥

This commit is contained in:
lyy
2016-09-26 22:36:30 +08:00
parent e586168e30
commit e4e80048e7
20 changed files with 305 additions and 231 deletions

8
.idea/gradle.xml generated
View File

@ -13,7 +13,13 @@
<option value="$PROJECT_DIR$/downloadutil" /> <option value="$PROJECT_DIR$/downloadutil" />
</set> </set>
</option> </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> </GradleProjectSettings>
</option> </option>
</component> </component>

2
.idea/misc.xml generated
View File

@ -53,7 +53,7 @@
<ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" /> <ConfirmationsSetting value="0" id="Remove" />
</component> </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" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">

1
.idea/modules.xml generated
View File

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

View File

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

View File

@ -2,15 +2,22 @@ package com.arialyy.downloadutil.core;
import android.content.Context; 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. * Created by lyy on 2016/8/11.
* 下载管理器,通过命令的方式控制下载 * 下载管理器,通过命令的方式控制下载
*/ */
public class DownloadManager { 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"; public static final String CURRENT_LOCATION = "CURRENT_LOCATION";
private List<IDownloadCommand> mCommands = new ArrayList<>();
private DownloadManager() {
}
private Context mContext; private Context mContext;
private DownloadManager(Context context) { private DownloadManager(Context context) {
@ -64,7 +77,42 @@ public class DownloadManager {
} }
public static DownloadManager getInstance(Context context) { 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();
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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