代码格式修改

This commit is contained in:
lyy
2016-09-27 09:28:50 +08:00
34 changed files with 2411 additions and 2482 deletions

17
.idea/misc.xml generated
View File

@ -53,25 +53,10 @@
<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_8" 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_7" 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">
<option name="id" value="Android" /> <option name="id" value="Android" />
</component> </component>
<component name="masterDetails">
<states>
<state key="ScopeChooserConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project> </project>

View File

@ -17,6 +17,10 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
} }
} }
dataBinding {
enabled = true
}
} }
dependencies { dependencies {
@ -24,5 +28,9 @@ dependencies {
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.+' compile 'com.android.support:appcompat-v7:23.+'
compile 'com.android.support:design:23.+' compile 'com.android.support:design:23.+'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.arialyy.frame:MVVM2:2.2.0'
compile project(':downloadutil') compile project(':downloadutil')
} }

View File

@ -25,14 +25,14 @@ public class MainActivity extends AppCompatActivity {
private static final int DOWNLOAD_RESUME = 0x05; private static final int DOWNLOAD_RESUME = 0x05;
private static final int DOWNLOAD_COMPLETE = 0x06; private static final int DOWNLOAD_COMPLETE = 0x06;
private ProgressBar mPb; private ProgressBar mPb;
private String mDownloadUrl = "http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk"; private String mDownloadUrl =
"http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk";
private DownLoadUtil mUtil; private DownLoadUtil mUtil;
private Button mStart, mStop, mCancel; private Button mStart, mStop, mCancel;
private TextView mSize; private TextView mSize;
private Handler mUpdateHandler = new Handler() { private Handler mUpdateHandler = new Handler() {
@Override @Override public void handleMessage(Message msg) {
public void handleMessage(Message msg) {
super.handleMessage(msg); super.handleMessage(msg);
switch (msg.what) { switch (msg.what) {
case DOWNLOAD_PRE: case DOWNLOAD_PRE:
@ -54,7 +54,8 @@ public class MainActivity extends AppCompatActivity {
mStart.setText("开始"); mStart.setText("开始");
break; break;
case DOWNLOAD_RESUME: case DOWNLOAD_RESUME:
Toast.makeText(MainActivity.this, "恢复下载,恢复位置 ==> " + Util.formatFileSize((Long) msg.obj), Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this, "恢复下载,恢复位置 ==> " + Util.formatFileSize((Long) msg.obj),
Toast.LENGTH_SHORT).show();
mStart.setEnabled(false); mStart.setEnabled(false);
break; break;
case DOWNLOAD_COMPLETE: case DOWNLOAD_COMPLETE:
@ -67,8 +68,7 @@ public class MainActivity extends AppCompatActivity {
} }
}; };
@Override @Override protected void onCreate(Bundle savedInstanceState) {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
@ -100,65 +100,56 @@ public class MainActivity extends AppCompatActivity {
} }
private void start() { private void start() {
mUtil.download(this, mDownloadUrl, Environment.getExternalStorageDirectory().getPath() + "/test.apk" mUtil.download(this, mDownloadUrl,
, new DownLoadUtil.DownloadListener() { Environment.getExternalStorageDirectory().getPath() + "/test.apk",
new DownLoadUtil.DownloadListener() {
long fileSize = 1; long fileSize = 1;
@Override @Override public void onPreDownload(HttpURLConnection connection) {
public void onPreDownload(HttpURLConnection connection) {
super.onPreDownload(connection); super.onPreDownload(connection);
mPb.setMax(100); mPb.setMax(100);
fileSize = connection.getContentLength(); fileSize = connection.getContentLength();
mUpdateHandler.obtainMessage(DOWNLOAD_PRE, fileSize).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_PRE, fileSize).sendToTarget();
} }
@Override @Override public void onStart(long startLocation) {
public void onStart(long startLocation) {
super.onStart(startLocation); super.onStart(startLocation);
} }
@Override @Override public void onChildResume(long resumeLocation) {
public void onChildResume(long resumeLocation) {
super.onChildResume(resumeLocation); super.onChildResume(resumeLocation);
} }
@Override @Override public void onChildComplete(long finishLocation) {
public void onChildComplete(long finishLocation) {
super.onChildComplete(finishLocation); super.onChildComplete(finishLocation);
} }
@Override @Override public void onProgress(long currentLocation) {
public void onProgress(long currentLocation) {
super.onProgress(currentLocation); super.onProgress(currentLocation);
mPb.setProgress((int) (currentLocation * 100 / fileSize)); mPb.setProgress((int) (currentLocation * 100 / fileSize));
} }
@Override @Override public void onStop(long stopLocation) {
public void onStop(long stopLocation) {
super.onStop(stopLocation); super.onStop(stopLocation);
mUpdateHandler.obtainMessage(DOWNLOAD_STOP).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_STOP).sendToTarget();
} }
@Override @Override public void onCancel() {
public void onCancel() {
super.onCancel(); super.onCancel();
mUpdateHandler.obtainMessage(DOWNLOAD_CANCEL).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_CANCEL).sendToTarget();
} }
@Override @Override public void onResume(long resumeLocation) {
public void onResume(long resumeLocation) {
super.onResume(resumeLocation); super.onResume(resumeLocation);
mUpdateHandler.obtainMessage(DOWNLOAD_RESUME, resumeLocation).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_RESUME, resumeLocation).sendToTarget();
} }
@Override @Override public void onFail() {
public void onFail() {
super.onFail(); super.onFail();
mUpdateHandler.obtainMessage(DOWNLOAD_FAILE).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_FAILE).sendToTarget();
} }
@Override @Override public void onComplete() {
public void onComplete() {
super.onComplete(); super.onComplete();
mUpdateHandler.obtainMessage(DOWNLOAD_COMPLETE).sendToTarget(); mUpdateHandler.obtainMessage(DOWNLOAD_COMPLETE).sendToTarget();
} }
@ -172,5 +163,4 @@ public class MainActivity extends AppCompatActivity {
private void cancel() { private void cancel() {
mUtil.cancelDownload(); mUtil.cancelDownload();
} }
} }

View File

@ -41,7 +41,8 @@ javadoc {
// 位置: 类 xxxx // 位置: 类 xxxx
android.libraryVariants.all { variant -> android.libraryVariants.all { variant ->
println variant.javaCompile.classpath.files println variant.javaCompile.classpath.files
if (variant.name == 'release') { //我们只需 release 的 javadoc if (variant.name == 'release') {
//我们只需 release 的 javadoc
task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) { task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
// title = '' // title = ''
// description = '' // description = ''
@ -55,7 +56,8 @@ android.libraryVariants.all { variant ->
exclude '**/BuildConfig.java' exclude '**/BuildConfig.java'
exclude '**/R.java' exclude '**/R.java'
} }
task("javadoc${variant.name.capitalize()}Jar", type: Jar, dependsOn: "generate${variant.name.capitalize()}Javadoc") { task("javadoc${variant.name.capitalize()}Jar", type: Jar,
dependsOn: "generate${variant.name.capitalize()}Javadoc") {
classifier = 'javadoc' classifier = 'javadoc'
from tasks.getByName("generate${variant.name.capitalize()}Javadoc").destinationDir from tasks.getByName("generate${variant.name.capitalize()}Javadoc").destinationDir
} }

View File

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

View File

@ -1,12 +1,17 @@
package com.arialyy.downloadutil.core; 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;
/** /**
* 下载开始前事件 * 下载开始前事件
*/ */
@ -57,6 +62,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 +75,37 @@ 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;
} }
/**
* 设置命令
*/
public void setCommant(IDownloadCommand command) {
mCommands.add(command);
}
/**
* 设置一组命令
*/
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

@ -1,9 +1,7 @@
package com.arialyy.downloadutil.core; package com.arialyy.downloadutil.core;
import android.content.Context; import android.content.Context;
import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -34,29 +32,25 @@ public class DownloadTarget extends IDownloadTarget {
mContext = context; mContext = context;
} }
@Override @Override public void startTask(Task task) {
public void startTask(Task task) {
if (mExecutePool.putTask(task)) { if (mExecutePool.putTask(task)) {
task.start(); task.start();
} }
} }
@Override @Override public void stopTask(Task task) {
public void stopTask(Task task) {
if (mExecutePool.removeTask(task)) { if (mExecutePool.removeTask(task)) {
task.stop(); task.stop();
} }
} }
@Override @Override public void cancelTask(Task task) {
public void cancelTask(Task task) {
if (mExecutePool.removeTask(task)) { if (mExecutePool.removeTask(task)) {
task.cancel(); task.cancel();
} }
} }
@Override @Override public void reTryStart(Task task) {
public void reTryStart(Task task) {
if (!task.getDownloadUtil().isDownloading()) { if (!task.getDownloadUtil().isDownloading()) {
task.start(); task.start();
} else { } else {
@ -64,15 +58,13 @@ public class DownloadTarget extends IDownloadTarget {
} }
} }
@Override @Override public Task createTask(DownloadEntity entity) {
public Task createTask(DownloadEntity entity) {
Task task = TaskFactory.getInstance().createTask(mContext, entity, mTaskHandler); Task task = TaskFactory.getInstance().createTask(mContext, entity, mTaskHandler);
mCachePool.putTask(task); mCachePool.putTask(task);
return task; return task;
} }
@Override @Override public Task getTask(DownloadEntity entity) {
public Task getTask(DownloadEntity entity) {
Task task = mExecutePool.getTask(entity.getDownloadUrl()); Task task = mExecutePool.getTask(entity.getDownloadUrl());
if (task == null) { if (task == null) {
task = mCachePool.getTask(entity.getDownloadUrl()); task = mCachePool.getTask(entity.getDownloadUrl());
@ -83,8 +75,7 @@ public class DownloadTarget extends IDownloadTarget {
return task; return task;
} }
@Override @Override public int getTaskState(DownloadEntity entity) {
public int getTaskState(DownloadEntity entity) {
Task task = getTask(entity); Task task = getTask(entity);
if (task == null) { if (task == null) {
Log.e(TAG, "没有找到下载链接为【" + entity.getDownloadUrl() + "】的下载任务"); Log.e(TAG, "没有找到下载链接为【" + entity.getDownloadUrl() + "】的下载任务");
@ -93,8 +84,7 @@ public class DownloadTarget extends IDownloadTarget {
return task.getDownloadEntity().getState(); return task.getDownloadEntity().getState();
} }
@Override @Override public void removeTask(DownloadEntity entity) {
public void removeTask(DownloadEntity entity) {
Task task = mCachePool.getTask(entity.getDownloadUrl()); Task task = mCachePool.getTask(entity.getDownloadUrl());
if (task != null) { if (task != null) {
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ? "成功" : "失败")); Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ? "成功" : "失败"));
@ -108,8 +98,7 @@ public class DownloadTarget extends IDownloadTarget {
} }
} }
@Override @Override public Task getNextTask() {
public Task getNextTask() {
return mCachePool.pollTask(); return mCachePool.pollTask();
} }
} }

View File

@ -3,7 +3,6 @@ package com.arialyy.downloadutil.core;
import android.os.Handler; import android.os.Handler;
import android.os.Message; import android.os.Message;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.inf.IDownloader; import com.arialyy.downloadutil.core.inf.IDownloader;
import com.arialyy.downloadutil.core.inf.ITask; import com.arialyy.downloadutil.core.inf.ITask;
import com.arialyy.downloadutil.core.pool.CachePool; import com.arialyy.downloadutil.core.pool.CachePool;
@ -60,36 +59,26 @@ public abstract class IDownloadTarget implements IDownloader, ITask {
public interface OnTargetListener { public interface OnTargetListener {
/** /**
* 任务开始 * 任务开始
*
* @param task
*/ */
public void onTaskStart(Task task); public void onTaskStart(Task task);
/** /**
* 任务停止 * 任务停止
*
* @param task
*/ */
public void onTaskStop(Task task); public void onTaskStop(Task task);
/** /**
* 任务取消 * 任务取消
*
* @param task
*/ */
public void onTaskCancel(Task task); public void onTaskCancel(Task task);
/** /**
* 任务下载失败 * 任务下载失败
*
* @param task
*/ */
public void onTaskFail(Task task); public void onTaskFail(Task task);
/** /**
* 任务完成 * 任务完成
*
* @param task
*/ */
public void onTaskComplete(Task task); public void onTaskComplete(Task task);
} }
@ -144,8 +133,7 @@ public abstract class IDownloadTarget implements IDownloader, ITask {
this.target = target; this.target = target;
} }
@Override @Override public void handleMessage(Message msg) {
public void handleMessage(Message msg) {
super.handleMessage(msg); super.handleMessage(msg);
DownloadEntity entity = (DownloadEntity) msg.obj; DownloadEntity entity = (DownloadEntity) msg.obj;
if (entity == null) { if (entity == null) {
@ -227,5 +215,4 @@ public abstract class IDownloadTarget implements IDownloader, ITask {
target.startTask(newTask); target.startTask(newTask);
} }
} }
} }

View File

@ -4,11 +4,9 @@ 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;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.IDownloadListener;
import com.arialyy.downloadutil.util.DownLoadUtil; import com.arialyy.downloadutil.util.DownLoadUtil;
import com.arialyy.downloadutil.util.IDownloadListener;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
/** /**
@ -38,7 +36,8 @@ public class Task {
if (listener == null) { if (listener == null) {
listener = new DownloadListener(context, downloadEntity, outHandler); listener = new DownloadListener(context, downloadEntity, outHandler);
} }
util.download(context, downloadEntity.getDownloadUrl(), downloadEntity.getDownloadPath(), listener); util.download(context, downloadEntity.getDownloadUrl(), downloadEntity.getDownloadPath(),
listener);
} }
} }
@ -88,8 +87,7 @@ public class Task {
sendIntent.addCategory(context.getPackageName()); sendIntent.addCategory(context.getPackageName());
} }
@Override @Override public void onPreDownload(HttpURLConnection connection) {
public void onPreDownload(HttpURLConnection connection) {
super.onPreDownload(connection); super.onPreDownload(connection);
long len = connection.getContentLength(); long len = connection.getContentLength();
downloadEntity.setFileSize(len); downloadEntity.setFileSize(len);
@ -97,23 +95,20 @@ public class Task {
sendIntent(DownloadManager.ACTION_PRE, -1); sendIntent(DownloadManager.ACTION_PRE, -1);
} }
@Override @Override public void onResume(long resumeLocation) {
public void onResume(long resumeLocation) {
super.onResume(resumeLocation); super.onResume(resumeLocation);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING); downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendIntent(DownloadManager.ACTION_RESUME, resumeLocation); sendIntent(DownloadManager.ACTION_RESUME, resumeLocation);
} }
@Override @Override public void onStart(long startLocation) {
public void onStart(long startLocation) {
super.onStart(startLocation); super.onStart(startLocation);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING); downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendInState2Target(IDownloadTarget.START); sendInState2Target(IDownloadTarget.START);
sendIntent(DownloadManager.ACTION_START, startLocation); sendIntent(DownloadManager.ACTION_START, startLocation);
} }
@Override @Override public void onProgress(long currentLocation) {
public void onProgress(long currentLocation) {
super.onProgress(currentLocation); super.onProgress(currentLocation);
if (currentLocation - lastLen > INTERVAL) { //不要太过于频繁发送广播 if (currentLocation - lastLen > INTERVAL) { //不要太过于频繁发送广播
sendIntent.putExtra(DownloadManager.ACTION_RUNNING, currentLocation); sendIntent.putExtra(DownloadManager.ACTION_RUNNING, currentLocation);
@ -121,16 +116,14 @@ public class Task {
} }
} }
@Override @Override public void onStop(long stopLocation) {
public void onStop(long stopLocation) {
super.onStop(stopLocation); super.onStop(stopLocation);
downloadEntity.setState(DownloadEntity.STATE_STOP); downloadEntity.setState(DownloadEntity.STATE_STOP);
sendInState2Target(IDownloadTarget.STOP); sendInState2Target(IDownloadTarget.STOP);
sendIntent(DownloadManager.ACTION_STOP, stopLocation); sendIntent(DownloadManager.ACTION_STOP, stopLocation);
} }
@Override @Override public void onCancel() {
public void onCancel() {
super.onCancel(); super.onCancel();
downloadEntity.setState(DownloadEntity.STATE_CANCEL); downloadEntity.setState(DownloadEntity.STATE_CANCEL);
sendInState2Target(IDownloadTarget.CANCEL); sendInState2Target(IDownloadTarget.CANCEL);
@ -138,8 +131,7 @@ public class Task {
downloadEntity.deleteData(); downloadEntity.deleteData();
} }
@Override @Override public void onComplete() {
public void onComplete() {
super.onComplete(); super.onComplete();
downloadEntity.setState(DownloadEntity.STATE_COMPLETE); downloadEntity.setState(DownloadEntity.STATE_COMPLETE);
downloadEntity.setDownloadComplete(true); downloadEntity.setDownloadComplete(true);
@ -147,8 +139,7 @@ public class Task {
sendIntent(DownloadManager.ACTION_COMPLETE, -1); sendIntent(DownloadManager.ACTION_COMPLETE, -1);
} }
@Override @Override public void onFail() {
public void onFail() {
super.onFail(); super.onFail();
downloadEntity.setState(DownloadEntity.STATE_FAIL); downloadEntity.setState(DownloadEntity.STATE_FAIL);
sendInState2Target(IDownloadTarget.FAIL); sendInState2Target(IDownloadTarget.FAIL);
@ -208,5 +199,4 @@ public class Task {
return task; return task;
} }
} }
} }

View File

@ -2,7 +2,6 @@ package com.arialyy.downloadutil.core;
import android.content.Context; import android.content.Context;
import android.os.Handler; import android.os.Handler;
import com.arialyy.downloadutil.entity.DownloadEntity; import com.arialyy.downloadutil.entity.DownloadEntity;
/** /**
@ -30,15 +29,13 @@ public class TaskFactory {
/** /**
* 创建普通下载任务 * 创建普通下载任务
* @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
*/ */
public Task createTask(Context context, DownloadEntity entity, Handler handler) { public Task createTask(Context context, DownloadEntity entity, Handler handler) {
Task.Builder builder = new Task.Builder(context, entity); Task.Builder builder = new Task.Builder(context, entity);
builder.setOutHandler(handler); builder.setOutHandler(handler);
return builder.builder(); return builder.builder();
} }
} }

View File

@ -13,8 +13,7 @@ class AddCommand extends IDownloadCommand {
super(context, entity); super(context, entity);
} }
@Override @Override public void executeComment() {
public void executeComment() {
target.createTask(mEntity); target.createTask(mEntity);
} }
} }

View File

@ -1,14 +1,10 @@
package com.arialyy.downloadutil.core.command; package com.arialyy.downloadutil.core.command;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull;
import com.arialyy.downloadutil.core.DownloadTarget; import com.arialyy.downloadutil.core.DownloadTarget;
import com.arialyy.downloadutil.core.IDownloadTarget; 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;
/** /**
* Created by lyy on 2016/8/22. * Created by lyy on 2016/8/22.
@ -49,6 +45,4 @@ public abstract class IDownloadCommand {
public void setDownloadTarget(IDownloadTarget downloadTarget) { public void setDownloadTarget(IDownloadTarget downloadTarget) {
target = downloadTarget; target = downloadTarget;
} }
} }

View File

@ -13,8 +13,7 @@ class StartCommand extends IDownloadCommand{
super(context, entity); super(context, entity);
} }
@Override @Override public void executeComment() {
public void executeComment() {
target.startTask(target.getTask(mEntity)); target.startTask(target.getTask(mEntity));
} }
} }

View File

@ -34,5 +34,4 @@ public interface IDownloader {
* @param task {@link Task} * @param task {@link Task}
*/ */
public void reTryStart(Task task); public void reTryStart(Task task);
} }

View File

@ -9,8 +9,6 @@ import com.arialyy.downloadutil.core.Task;
public interface IPool { public interface IPool {
/** /**
* 将下载任务添加到任务池中 * 将下载任务添加到任务池中
*
* @param task
*/ */
public boolean putTask(Task task); public boolean putTask(Task task);

View File

@ -35,6 +35,7 @@ public interface ITask {
/** /**
* 通过下载链接删除任务 * 通过下载链接删除任务
*
* @param entity 下载实体{@link DownloadEntity} * @param entity 下载实体{@link DownloadEntity}
*/ */
public void removeTask(DownloadEntity entity); public void removeTask(DownloadEntity entity);
@ -45,5 +46,4 @@ public interface ITask {
* @return 下载任务 or null * @return 下载任务 or null
*/ */
public Task getNextTask(); public Task getNextTask();
} }

View File

@ -2,11 +2,9 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.core.Task;
import com.arialyy.downloadutil.core.inf.IPool; import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.PriorityQueue; import java.util.PriorityQueue;
@ -37,8 +35,7 @@ public class CachePool implements IPool {
mCacheArray = new HashMap<>(); mCacheArray = new HashMap<>();
} }
@Override @Override public boolean putTask(Task task) {
public boolean putTask(Task task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {
Log.e(TAG, "下载任务不能为空!!"); Log.e(TAG, "下载任务不能为空!!");
@ -59,8 +56,7 @@ public class CachePool implements IPool {
} }
} }
@Override @Override public Task pollTask() {
public Task pollTask() {
synchronized (LOCK) { synchronized (LOCK) {
Task task = mCacheQueue.poll(); Task task = mCacheQueue.poll();
if (task != null) { if (task != null) {
@ -71,8 +67,7 @@ public class CachePool implements IPool {
} }
} }
@Override @Override public Task getTask(String downloadUrl) {
public Task getTask(String downloadUrl) {
synchronized (LOCK) { synchronized (LOCK) {
if (TextUtils.isEmpty(downloadUrl)) { if (TextUtils.isEmpty(downloadUrl)) {
Log.e(TAG, "请传入有效的下载链接"); Log.e(TAG, "请传入有效的下载链接");
@ -83,8 +78,7 @@ public class CachePool implements IPool {
} }
} }
@Override @Override public boolean removeTask(Task task) {
public boolean removeTask(Task task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {
Log.e(TAG, "任务不能为空"); Log.e(TAG, "任务不能为空");
@ -97,8 +91,7 @@ public class CachePool implements IPool {
} }
} }
@Override @Override public boolean removeTask(String downloadUrl) {
public boolean removeTask(String downloadUrl) {
synchronized (LOCK) { synchronized (LOCK) {
if (TextUtils.isEmpty(downloadUrl)) { if (TextUtils.isEmpty(downloadUrl)) {
Log.e(TAG, "请传入有效的下载链接"); Log.e(TAG, "请传入有效的下载链接");
@ -111,8 +104,7 @@ public class CachePool implements IPool {
} }
} }
@Override @Override public int size() {
public int size() {
return mCacheQueue.size(); return mCacheQueue.size();
} }
} }

View File

@ -2,11 +2,9 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.core.Task; import com.arialyy.downloadutil.core.Task;
import com.arialyy.downloadutil.core.inf.IPool; import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
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;
@ -39,8 +37,7 @@ public class ExecutePool implements IPool {
mExecuteArray = new HashMap<>(); mExecuteArray = new HashMap<>();
} }
@Override @Override public boolean putTask(Task task) {
public boolean putTask(Task task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {
Log.e(TAG, "下载任务不能为空!!"); Log.e(TAG, "下载任务不能为空!!");
@ -100,8 +97,7 @@ public class ExecutePool implements IPool {
return true; return true;
} }
@Override @Override public Task pollTask() {
public Task pollTask() {
synchronized (LOCK) { synchronized (LOCK) {
Task task = mExecuteQueue.poll(); Task task = mExecuteQueue.poll();
if (task != null) { if (task != null) {
@ -112,8 +108,7 @@ public class ExecutePool implements IPool {
} }
} }
@Override @Override public Task getTask(String downloadUrl) {
public Task getTask(String downloadUrl) {
synchronized (LOCK) { synchronized (LOCK) {
if (TextUtils.isEmpty(downloadUrl)) { if (TextUtils.isEmpty(downloadUrl)) {
Log.e(TAG, "请传入有效的下载链接"); Log.e(TAG, "请传入有效的下载链接");
@ -124,8 +119,7 @@ public class ExecutePool implements IPool {
} }
} }
@Override @Override public boolean removeTask(Task task) {
public boolean removeTask(Task task) {
synchronized (LOCK) { synchronized (LOCK) {
if (task == null) { if (task == null) {
Log.e(TAG, "任务不能为空"); Log.e(TAG, "任务不能为空");
@ -138,8 +132,7 @@ public class ExecutePool implements IPool {
} }
} }
@Override @Override public boolean removeTask(String downloadUrl) {
public boolean removeTask(String downloadUrl) {
synchronized (LOCK) { synchronized (LOCK) {
if (TextUtils.isEmpty(downloadUrl)) { if (TextUtils.isEmpty(downloadUrl)) {
Log.e(TAG, "请传入有效的下载链接"); Log.e(TAG, "请传入有效的下载链接");
@ -152,9 +145,7 @@ public class ExecutePool implements IPool {
} }
} }
@Override @Override public int size() {
public int size() {
return mExecuteQueue.size(); return mExecuteQueue.size();
} }
} }

View File

@ -2,7 +2,6 @@ package com.arialyy.downloadutil.entity;
import android.os.Parcel; import android.os.Parcel;
import android.os.Parcelable; import android.os.Parcelable;
import com.arialyy.downloadutil.orm.DbEntity; import com.arialyy.downloadutil.orm.DbEntity;
/** /**
@ -130,22 +129,18 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
this.currentProgress = currentProgress; this.currentProgress = currentProgress;
} }
@Override @Override public DownloadEntity clone() throws CloneNotSupportedException {
public DownloadEntity clone() throws CloneNotSupportedException {
return (DownloadEntity) super.clone(); return (DownloadEntity) super.clone();
} }
public DownloadEntity() { public DownloadEntity() {
} }
@Override @Override public int describeContents() {
public int describeContents() {
return 0; return 0;
} }
@Override @Override public void writeToParcel(Parcel dest, int flags) {
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.downloadUrl); dest.writeString(this.downloadUrl);
dest.writeString(this.downloadPath); dest.writeString(this.downloadPath);
dest.writeLong(this.completeTime); dest.writeLong(this.completeTime);
@ -168,19 +163,16 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
} }
public static final Creator<DownloadEntity> CREATOR = new Creator<DownloadEntity>() { public static final Creator<DownloadEntity> CREATOR = new Creator<DownloadEntity>() {
@Override @Override public DownloadEntity createFromParcel(Parcel source) {
public DownloadEntity createFromParcel(Parcel source) {
return new DownloadEntity(source); return new DownloadEntity(source);
} }
@Override @Override public DownloadEntity[] newArray(int size) {
public DownloadEntity[] newArray(int size) {
return new DownloadEntity[size]; return new DownloadEntity[size];
} }
}; };
@Override @Override public String toString() {
public String toString() {
return "DownloadEntity{" + return "DownloadEntity{" +
"downloadUrl='" + downloadUrl + '\'' + "downloadUrl='" + downloadUrl + '\'' +
", downloadPath='" + downloadPath + '\'' + ", downloadPath='" + downloadPath + '\'' +

View File

@ -1,6 +1,5 @@
package com.arialyy.downloadutil.help; package com.arialyy.downloadutil.help;
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;

View File

@ -4,10 +4,7 @@ import android.content.Context;
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;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -119,7 +116,8 @@ public class DbEntity {
* *
* @return 没有数据返回null * @return 没有数据返回null
*/ */
public <T extends DbEntity> List<T> findDatas(Class<T> clazz, @NonNull Object[] wheres, @NonNull Object[] values) { public <T extends DbEntity> List<T> findDatas(Class<T> clazz, @NonNull Object[] wheres,
@NonNull Object[] values) {
Cursor cursor = mUtil.findData(this, wheres, values); Cursor cursor = mUtil.findData(this, wheres, values);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
} }
@ -129,7 +127,8 @@ public class DbEntity {
* *
* @return 没有数据返回null * @return 没有数据返回null
*/ */
public <T extends DbEntity> T findData(Class<T> clazz, @NonNull Object[] wheres, @NonNull Object[] values) { public <T extends DbEntity> T findData(Class<T> clazz, @NonNull Object[] wheres,
@NonNull Object[] values) {
Cursor cursor = mUtil.findData(this, wheres, values); Cursor cursor = mUtil.findData(this, wheres, values);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor).get(0) : null; return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor).get(0) : null;
} }
@ -190,6 +189,4 @@ public class DbEntity {
cursor.close(); cursor.close();
return entitys; return entitys;
} }
} }

View File

@ -1,11 +1,10 @@
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;
import android.util.Log; import android.util.Log;
import com.arialyy.downloadutil.util.Util; import com.arialyy.downloadutil.util.Util;
import java.lang.reflect.Field; import java.lang.reflect.Field;
/** /**
@ -66,7 +65,6 @@ public class DbUtil {
} }
print(DEL_DATA, sb.toString()); print(DEL_DATA, sb.toString());
mDb.execSQL(sb.toString()); mDb.execSQL(sb.toString());
} }
/** /**
@ -87,7 +85,10 @@ public class DbUtil {
} }
sb.append(i > 0 ? ", " : ""); sb.append(i > 0 ? ", " : "");
try { try {
sb.append(field.getName()).append(" = '").append(field.get(dbEntity).toString()).append("'"); sb.append(field.getName())
.append(" = '")
.append(field.get(dbEntity).toString())
.append("'");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -108,7 +109,6 @@ public class DbUtil {
return mDb.rawQuery(sb.toString(), null); return mDb.rawQuery(sb.toString(), null);
} }
/** /**
* 条件查寻数据 * 条件查寻数据
*/ */
@ -196,24 +196,19 @@ public class DbUtil {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (cursor != null) if (cursor != null) cursor.close();
cursor.close();
} }
return false; return false;
} }
/** /**
* 创建表 * 创建表
*
* @param dbEntity
*/ */
protected void createTable(DbEntity dbEntity) { protected void createTable(DbEntity dbEntity) {
Field[] fields = Util.getFields(dbEntity.getClass()); Field[] fields = Util.getFields(dbEntity.getClass());
if (fields != null && fields.length > 0) { if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("create table ") sb.append("create table ").append(Util.getClassName(dbEntity)).append("(");
.append(Util.getClassName(dbEntity))
.append("(");
int i = 0; int i = 0;
int ignoreNum = 0; int ignoreNum = 0;
for (Field field : fields) { for (Field field : fields) {
@ -255,7 +250,6 @@ public class DbUtil {
* 打印数据库日志 * 打印数据库日志
* *
* @param type {@link DbUtil} * @param type {@link DbUtil}
* @param sql
*/ */
private void print(int type, String sql) { private void print(int type, String sql) {
String str = ""; String str = "";
@ -302,8 +296,6 @@ public class DbUtil {
/** /**
* 获取行Id * 获取行Id
*
* @return
*/ */
protected int getRowId(DbEntity dbEntity, Object[] wheres, Object[] values) { protected int getRowId(DbEntity dbEntity, Object[] wheres, Object[] values) {
if (wheres.length <= 0 || values.length <= 0) { if (wheres.length <= 0 || values.length <= 0) {

View File

@ -9,8 +9,6 @@ import java.lang.annotation.Target;
* Created by lyy on 2015/11/2. * Created by lyy on 2015/11/2.
* 表ID字段指定 * 表ID字段指定
*/ */
@Target(ElementType.FIELD) @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Id {
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
int value() default -1; int value() default -1;
} }

View File

@ -9,8 +9,6 @@ import java.lang.annotation.Target;
* Created by lyy on 2015/11/2. * Created by lyy on 2015/11/2.
* 忽略某个字段 * 忽略某个字段
*/ */
@Target(ElementType.FIELD) @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Ignore {
@Retention(RetentionPolicy.RUNTIME)
public @interface Ignore {
boolean value() default false; boolean value() default false;
} }

View File

@ -26,13 +26,11 @@ public class SqlHelper extends SQLiteOpenHelper {
super(context, DB_NAME, null, VERSION); super(context, DB_NAME, null, VERSION);
} }
@Override @Override public void onCreate(SQLiteDatabase db) {
public void onCreate(SQLiteDatabase db) {
} }
@Override @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
} }
} }

View File

@ -4,7 +4,6 @@ import android.content.Context;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.util.Log; import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -13,6 +12,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.
* 下载工具类 * 下载工具类
@ -37,34 +37,39 @@ public class DownLoadUtil {
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;
} }
/** /**
* 获取当前下载位置 * 获取当前下载位置
*
* @return
*/ */
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;
} }
/** /**
* 多线程断点续传下载文件,暂停和继续 * 多线程断点续传下载文件,暂停和继续
* *
@ -73,8 +78,8 @@ public class DownLoadUtil {
* @param filePath 保存路径 * @param filePath 保存路径
* @param downloadListener 下载进度监听 {@link DownloadListener} * @param downloadListener 下载进度监听 {@link DownloadListener}
*/ */
public void download(final Context context, @NonNull final String downloadUrl, @NonNull final String filePath, public void download(final Context context, @NonNull final String downloadUrl,
@NonNull final IDownloadListener downloadListener) { @NonNull final String filePath, @NonNull final IDownloadListener downloadListener) {
isDownloading = true; isDownloading = true;
mCurrentLocation = 0; mCurrentLocation = 0;
isStop = false; isStop = false;
@ -83,7 +88,8 @@ public class DownLoadUtil {
mStopNum = 0; mStopNum = 0;
final File dFile = new File(filePath); final File dFile = new File(filePath);
//读取已完成的线程数 //读取已完成的线程数
final File configFile = new File(context.getFilesDir().getPath() + "/temp/" + dFile.getName() + ".properties"); final File configFile =
new File(context.getFilesDir().getPath() + "/temp/" + dFile.getName() + ".properties");
try { try {
if (!configFile.exists()) { //记录文件被删除,则重新下载 if (!configFile.exists()) { //记录文件被删除,则重新下载
isNewTask = true; isNewTask = true;
@ -97,8 +103,7 @@ public class DownLoadUtil {
return; return;
} }
new Thread(new Runnable() { new Thread(new Runnable() {
@Override @Override public void run() {
public void run() {
try { try {
mListener = downloadListener; mListener = downloadListener;
URL url = new URL(downloadUrl); URL url = new URL(downloadUrl);
@ -106,8 +111,10 @@ public class DownLoadUtil {
conn.setRequestMethod("GET"); conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Charset", "UTF-8");
conn.setConnectTimeout(TIME_OUT * 4); conn.setConnectTimeout(TIME_OUT * 4);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("User-Agent",
conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
conn.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
conn.connect(); conn.connect();
int len = conn.getContentLength(); int len = conn.getContentLength();
if (len < 0) { //网络被劫持时会出现这个问题 if (len < 0) { //网络被劫持时会出现这个问题
@ -168,7 +175,9 @@ public class DownLoadUtil {
} }
//分配下载位置 //分配下载位置
Object record = pro.getProperty(dFile.getName() + "_record_" + i); Object record = pro.getProperty(dFile.getName() + "_record_" + i);
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 + "");
mCurrentLocation += r - startL; mCurrentLocation += r - startL;
Log.d(TAG, "++++++++++ 线程_" + i + "_恢复下载 ++++++++++"); Log.d(TAG, "++++++++++ 线程_" + i + "_恢复下载 ++++++++++");
@ -186,7 +195,8 @@ public class DownLoadUtil {
if (i == (THREAD_NUM - 1)) { if (i == (THREAD_NUM - 1)) {
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));
} }
@ -206,11 +216,17 @@ public class DownLoadUtil {
failDownload("下载失败,返回码:" + code); failDownload("下载失败,返回码:" + code);
} }
} catch (IOException e) { } catch (IOException e) {
failDownload("下载失败【downloadUrl:" + downloadUrl + "\n【filePath:" + filePath + "" + Util.getPrintException(e)); failDownload("下载失败【downloadUrl:"
+ downloadUrl
+ "\n【filePath:"
+ filePath
+ ""
+ Util.getPrintException(e));
} }
} }
}).start(); }).start();
} }
private void failDownload(String msg) { private void failDownload(String msg) {
Log.e(TAG, msg); Log.e(TAG, msg);
isDownloading = false; isDownloading = false;
@ -218,6 +234,7 @@ public class DownLoadUtil {
mListener.onFail(); mListener.onFail();
System.gc(); System.gc();
} }
/** /**
* 多线程下载任务类,不能使用AsyncTask来进行多线程下载因为AsyncTask是串行执行的这种方式下载速度太慢了 * 多线程下载任务类,不能使用AsyncTask来进行多线程下载因为AsyncTask是串行执行的这种方式下载速度太慢了
*/ */
@ -225,24 +242,38 @@ public class DownLoadUtil {
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
public void run() { @Override 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);
conn.setRequestMethod("GET"); conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Charset", "UTF-8");
conn.setConnectTimeout(TIME_OUT * 4); conn.setConnectTimeout(TIME_OUT * 4);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("User-Agent",
conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
conn.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
conn.setReadTimeout(TIME_OUT * 24); //设置读取流的等待时间,必须设置该参数 conn.setReadTimeout(TIME_OUT * 24); //设置读取流的等待时间,必须设置该参数
InputStream is = conn.getInputStream(); InputStream is = conn.getInputStream();
//创建可设置位置的文件 //创建可设置位置的文件
@ -295,7 +326,8 @@ public class DownLoadUtil {
synchronized (DownLoadUtil.this) { synchronized (DownLoadUtil.this) {
mStopNum++; mStopNum++;
String location = String.valueOf(currentLocation); String location = String.valueOf(currentLocation);
Log.i(TAG, "thread_" + dEntity.threadId + "_stop, stop location ==> " + currentLocation); Log.i(TAG,
"thread_" + dEntity.threadId + "_stop, stop location ==> " + currentLocation);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId, location); writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId, location);
if (mStopNum == THREAD_NUM) { if (mStopNum == THREAD_NUM) {
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++"); Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
@ -353,10 +385,9 @@ public class DownLoadUtil {
} }
} }
} }
/** /**
* 将记录写入到配置文件 * 将记录写入到配置文件
*
* @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);
@ -365,6 +396,7 @@ public class DownLoadUtil {
Util.saveConfig(configFile, pro); Util.saveConfig(configFile, pro);
} }
} }
/** /**
* 子线程下载信息类 * 子线程下载信息类
*/ */
@ -377,7 +409,9 @@ public class DownLoadUtil {
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;
this.tempFile = file; this.tempFile = file;
@ -390,53 +424,43 @@ public class DownLoadUtil {
public static class DownloadListener implements IDownloadListener { public static class DownloadListener implements IDownloadListener {
@Override @Override public void onResume(long resumeLocation) {
public void onResume(long resumeLocation) {
} }
@Override @Override public void onCancel() {
public void onCancel() {
} }
@Override @Override public void onFail() {
public void onFail() {
} }
@Override @Override public void onPreDownload(HttpURLConnection connection) {
public void onPreDownload(HttpURLConnection connection) {
} }
@Override @Override public void onProgress(long currentLocation) {
public void onProgress(long currentLocation) {
} }
@Override @Override public void onChildComplete(long finishLocation) {
public void onChildComplete(long finishLocation) {
} }
@Override @Override public void onStart(long startLocation) {
public void onStart(long startLocation) {
} }
@Override @Override public void onChildResume(long resumeLocation) {
public void onChildResume(long resumeLocation) {
} }
@Override @Override public void onStop(long stopLocation) {
public void onStop(long stopLocation) {
} }
@Override @Override public void onComplete() {
public void onComplete() {
} }
} }

View File

@ -55,5 +55,4 @@ public interface IDownloadListener {
* 下载完成 * 下载完成
*/ */
public void onComplete(); public void onComplete();
} }

View File

@ -1,13 +1,10 @@
package com.arialyy.downloadutil.util; package com.arialyy.downloadutil.util;
import android.util.Log; import android.util.Log;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
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.lang.reflect.Field; import java.lang.reflect.Field;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.security.MessageDigest; import java.security.MessageDigest;
@ -40,9 +37,6 @@ public class Util {
/** /**
* 将普通字符串转换为16位进制字符串 * 将普通字符串转换为16位进制字符串
*
* @param src
* @return
*/ */
public static String bytesToHexString(byte[] src) { public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("0x"); StringBuilder stringBuilder = new StringBuilder("0x");
@ -88,7 +82,6 @@ public class Util {
* 格式化文件大小 * 格式化文件大小
* *
* @param size file.length() 获取文件大小 * @param size file.length() 获取文件大小
* @return
*/ */
public static String formatFileSize(double size) { public static String formatFileSize(double size) {
double kiloByte = size / 1024; double kiloByte = size / 1024;
@ -119,9 +112,6 @@ public class Util {
/** /**
* 创建目录 当目录不存在的时候创建文件否则返回false * 创建目录 当目录不存在的时候创建文件否则返回false
*
* @param path
* @return
*/ */
public static boolean createDir(String path) { public static boolean createDir(String path) {
File file = new File(path); File file = new File(path);
@ -137,9 +127,6 @@ public class Util {
/** /**
* 创建文件 当文件不存在的时候就创建一个文件,否则直接返回文件 * 创建文件 当文件不存在的时候就创建一个文件,否则直接返回文件
*
* @param path
* @return
*/ */
public static File createFile(String path) { public static File createFile(String path) {
File file = new File(path); File file = new File(path);
@ -194,9 +181,6 @@ public class Util {
/** /**
* 读取下载配置文件 * 读取下载配置文件
*
* @param file
* @return
*/ */
public static Properties loadConfig(File file) { public static Properties loadConfig(File file) {
Properties properties = new Properties(); Properties properties = new Properties();
@ -220,9 +204,6 @@ public class Util {
/** /**
* 保存配置文件 * 保存配置文件
*
* @param file
* @param properties
*/ */
public static void saveConfig(File file, Properties properties) { public static void saveConfig(File file, Properties properties) {
FileOutputStream fos = null; FileOutputStream fos = null;

View File

@ -2,14 +2,13 @@ package com.arialyy.downloadutil;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
/** /**
* To work on unit tests, switch the Test Artifact in the Build Variants view. * To work on unit tests, switch the Test Artifact in the Build Variants view.
*/ */
public class ExampleUnitTest { public class ExampleUnitTest {
@Test @Test public void addition_isCorrect() throws Exception {
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2); assertEquals(4, 2 + 2);
} }
} }