代码格式修改

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="Remove" />
</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" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</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>

View File

@ -17,6 +17,10 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
@ -24,5 +28,9 @@ dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7: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')
}

View File

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

View File

@ -41,7 +41,8 @@ javadoc {
// 位置: 类 xxxx
android.libraryVariants.all { variant ->
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) {
// title = ''
// description = ''
@ -55,7 +56,8 @@ android.libraryVariants.all { variant ->
exclude '**/BuildConfig.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'
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;
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;
/**
* 下载开始前事件
*/
@ -57,6 +62,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 +75,37 @@ 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;
}
/**
* 设置命令
*/
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;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -34,29 +32,25 @@ public class DownloadTarget extends IDownloadTarget {
mContext = context;
}
@Override
public void startTask(Task task) {
@Override public void startTask(Task task) {
if (mExecutePool.putTask(task)) {
task.start();
}
}
@Override
public void stopTask(Task task) {
@Override public void stopTask(Task task) {
if (mExecutePool.removeTask(task)) {
task.stop();
}
}
@Override
public void cancelTask(Task task) {
@Override public void cancelTask(Task task) {
if (mExecutePool.removeTask(task)) {
task.cancel();
}
}
@Override
public void reTryStart(Task task) {
@Override public void reTryStart(Task task) {
if (!task.getDownloadUtil().isDownloading()) {
task.start();
} else {
@ -64,27 +58,24 @@ public class DownloadTarget extends IDownloadTarget {
}
}
@Override
public Task createTask(DownloadEntity entity) {
@Override public Task createTask(DownloadEntity entity) {
Task task = TaskFactory.getInstance().createTask(mContext, entity, mTaskHandler);
mCachePool.putTask(task);
return task;
}
@Override
public Task getTask(DownloadEntity entity) {
@Override public Task getTask(DownloadEntity entity) {
Task task = mExecutePool.getTask(entity.getDownloadUrl());
if (task == null) {
task = mCachePool.getTask(entity.getDownloadUrl());
}
if (task == null){
if (task == null) {
task = createTask(entity);
}
return task;
}
@Override
public int getTaskState(DownloadEntity entity) {
@Override public int getTaskState(DownloadEntity entity) {
Task task = getTask(entity);
if (task == null) {
Log.e(TAG, "没有找到下载链接为【" + entity.getDownloadUrl() + "】的下载任务");
@ -93,8 +84,7 @@ public class DownloadTarget extends IDownloadTarget {
return task.getDownloadEntity().getState();
}
@Override
public void removeTask(DownloadEntity entity) {
@Override public void removeTask(DownloadEntity entity) {
Task task = mCachePool.getTask(entity.getDownloadUrl());
if (task != null) {
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ? "成功" : "失败"));
@ -108,8 +98,7 @@ public class DownloadTarget extends IDownloadTarget {
}
}
@Override
public Task getNextTask() {
@Override public Task getNextTask() {
return mCachePool.pollTask();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,14 +7,13 @@ 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);
}
@Override
public void executeComment() {
@Override public void executeComment() {
target.startTask(target.getTask(mEntity));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package com.arialyy.downloadutil.help;
import android.app.Application;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
@ -28,20 +27,20 @@ public class CheckHelp {
} 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())){
} 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())){
} 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(" ")){
if (fileName.contains(" ")) {
fileName = fileName.replace(" ", "_");
}
String dPath = entity.getDownloadPath();
File file = new File(dPath);
if (file.isDirectory()){
if (file.isDirectory()) {
dPath += fileName;
entity.setDownloadPath(dPath);
}

View File

@ -4,10 +4,7 @@ import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import com.arialyy.downloadutil.util.Util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
@ -80,7 +77,7 @@ public class DbEntity {
* 删除当前数据
*/
public void deleteData() {
mUtil.delData(this, new Object[]{"rowid"}, new Object[]{rowID});
mUtil.delData(this, new Object[] { "rowid" }, new Object[] { rowID });
}
/**
@ -119,7 +116,8 @@ public class DbEntity {
*
* @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);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
}
@ -129,7 +127,8 @@ public class DbEntity {
*
* @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);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor).get(0) : null;
}
@ -143,8 +142,8 @@ public class DbEntity {
if (fields != null && fields.length > 0) {
try {
while (cursor.moveToNext()) {
Class[] paramTypes = {Context.class, boolean.class};
Object[] params = {mContext, false};
Class[] paramTypes = { Context.class, boolean.class };
Object[] params = { mContext, false };
Constructor<T> con = clazz.getConstructor(paramTypes);
T entity = con.newInstance(params);
for (Field field : fields) {
@ -172,7 +171,7 @@ public class DbEntity {
} else if (type == byte[].class) {
field.set(entity, cursor.getBlob(column));
}
// field.set(entity, cursor.getColumnIndex("entity_id"));
// field.set(entity, cursor.getColumnIndex("entity_id"));
}
entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid"));
entitys.add(entity);
@ -190,6 +189,4 @@ public class DbEntity {
cursor.close();
return entitys;
}
}

View File

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

View File

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

View File

@ -26,13 +26,11 @@ public class SqlHelper extends SQLiteOpenHelper {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
@Override public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@Override 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.util.Log;
import android.util.SparseArray;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@ -13,6 +12,7 @@ import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
/**
* Created by lyy on 2015/8/25.
* 下载工具类
@ -37,34 +37,39 @@ public class DownLoadUtil {
boolean isNewTask = true;
private int mCancelNum = 0;
private int mStopNum = 0;
public DownLoadUtil() {
}
public IDownloadListener getListener(){
public IDownloadListener getListener() {
return mListener;
}
/**
* 获取当前下载位置
*
* @return
*/
public long getCurrentLocation() {
return mCurrentLocation;
}
public boolean isDownloading() {
return isDownloading;
}
/**
* 取消下载
*/
public void cancelDownload() {
isCancel = true;
}
/**
* 停止下载
*/
public void stopDownload() {
isStop = true;
}
/**
* 多线程断点续传下载文件,暂停和继续
*
@ -73,8 +78,8 @@ public class DownLoadUtil {
* @param filePath 保存路径
* @param downloadListener 下载进度监听 {@link DownloadListener}
*/
public void download(final Context context, @NonNull final String downloadUrl, @NonNull final String filePath,
@NonNull final IDownloadListener downloadListener) {
public void download(final Context context, @NonNull final String downloadUrl,
@NonNull final String filePath, @NonNull final IDownloadListener downloadListener) {
isDownloading = true;
mCurrentLocation = 0;
isStop = false;
@ -83,7 +88,8 @@ public class DownLoadUtil {
mStopNum = 0;
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 {
if (!configFile.exists()) { //记录文件被删除,则重新下载
isNewTask = true;
@ -97,8 +103,7 @@ public class DownLoadUtil {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
mListener = downloadListener;
URL url = new URL(downloadUrl);
@ -106,8 +111,10 @@ public class DownLoadUtil {
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
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("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.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("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();
int len = conn.getContentLength();
if (len < 0) { //网络被劫持时会出现这个问题
@ -168,7 +175,9 @@ public class DownLoadUtil {
}
//分配下载位置
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 + "");
mCurrentLocation += r - startL;
Log.d(TAG, "++++++++++ 线程_" + i + "_恢复下载 ++++++++++");
@ -176,7 +185,7 @@ public class DownLoadUtil {
startL = r;
recordL[rl] = i;
rl++;
}else {
} else {
isNewTask = true;
}
if (isNewTask) {
@ -186,7 +195,8 @@ public class DownLoadUtil {
if (i == (THREAD_NUM - 1)) {
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);
tasks.put(i, new Thread(task));
}
@ -206,18 +216,25 @@ public class DownLoadUtil {
failDownload("下载失败,返回码:" + code);
}
} catch (IOException e) {
failDownload("下载失败【downloadUrl:" + downloadUrl + "\n【filePath:" + filePath + "" + Util.getPrintException(e));
failDownload("下载失败【downloadUrl:"
+ downloadUrl
+ "\n【filePath:"
+ filePath
+ ""
+ Util.getPrintException(e));
}
}
}).start();
}
private void failDownload(String msg){
private void failDownload(String msg) {
Log.e(TAG, msg);
isDownloading = false;
stopDownload();
mListener.onFail();
System.gc();
}
/**
* 多线程下载任务类,不能使用AsyncTask来进行多线程下载因为AsyncTask是串行执行的这种方式下载速度太慢了
*/
@ -225,24 +242,38 @@ public class DownLoadUtil {
private static final String TAG = "DownLoadTask";
private DownloadEntity dEntity;
private String configFPath;
public DownLoadTask(DownloadEntity 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;
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);
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.setRequestProperty("Charset", "UTF-8");
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("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.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("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); //设置读取流的等待时间,必须设置该参数
InputStream is = conn.getInputStream();
//创建可设置位置的文件
@ -295,7 +326,8 @@ public class DownLoadUtil {
synchronized (DownLoadUtil.this) {
mStopNum++;
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);
if (mStopNum == THREAD_NUM) {
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
@ -353,10 +385,9 @@ public class DownLoadUtil {
}
}
}
/**
* 将记录写入到配置文件
*
* @param record
*/
private void writeConfig(String key, String record) throws IOException {
File configFile = new File(configFPath);
@ -365,6 +396,7 @@ public class DownLoadUtil {
Util.saveConfig(configFile, pro);
}
}
/**
* 子线程下载信息类
*/
@ -377,7 +409,9 @@ public class DownLoadUtil {
long endLocation;
File tempFile;
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.downloadUrl = downloadUrl;
this.tempFile = file;
@ -390,53 +424,43 @@ public class DownLoadUtil {
public static class DownloadListener implements IDownloadListener {
@Override
public void onResume(long resumeLocation) {
@Override public void onResume(long resumeLocation) {
}
@Override
public void onCancel() {
@Override public void onCancel() {
}
@Override
public void onFail() {
@Override public void onFail() {
}
@Override
public void onPreDownload(HttpURLConnection connection) {
@Override public void onPreDownload(HttpURLConnection connection) {
}
@Override
public void onProgress(long currentLocation) {
@Override public void onProgress(long currentLocation) {
}
@Override
public void onChildComplete(long finishLocation) {
@Override public void onChildComplete(long finishLocation) {
}
@Override
public void onStart(long startLocation) {
@Override public void onStart(long startLocation) {
}
@Override
public void onChildResume(long resumeLocation) {
@Override public void onChildResume(long resumeLocation) {
}
@Override
public void onStop(long stopLocation) {
@Override public void onStop(long stopLocation) {
}
@Override
public void onComplete() {
@Override public void onComplete() {
}
}

View File

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

View File

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

View File

@ -2,14 +2,13 @@ package com.arialyy.downloadutil;
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.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
@Test public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}