例子编写

This commit is contained in:
lyy
2016-09-27 22:41:35 +08:00
parent 3496022c60
commit 2ad2f31594
53 changed files with 2793 additions and 2592 deletions

2
.idea/misc.xml generated
View File

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

View File

@ -1,10 +1,14 @@
package com.arialyy.simple.activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.arialyy.simple.R;
import com.arialyy.simple.adapter.DownloadAdapter;
import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivityMainBinding;
import com.arialyy.simple.module.DownloadModule;
import butterknife.Bind;
@ -13,10 +17,16 @@ import butterknife.Bind;
*/
public class MainActivity extends BaseActivity<ActivityMainBinding> {
@Bind(R.id.list) RecyclerView mList;
DownloadAdapter mAdapter;
@Override protected int setLayoutId() {
return R.layout.activity_main;
}
@Override protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
mAdapter = new DownloadAdapter(this, getModule(DownloadModule.class).getDownloadData());
mList.setLayoutManager(new LinearLayoutManager(this));
mList.setAdapter(mAdapter);
}
}

View File

@ -1,5 +1,8 @@
package com.arialyy.simple.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
@ -11,13 +14,19 @@ import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.core.command.CommandFactory;
import com.arialyy.downloadutil.core.command.IDownloadCommand;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.DownLoadUtil;
import com.arialyy.downloadutil.util.Util;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseActivity;
import com.arialyy.simple.databinding.ActivitySimpleBinding;
import com.arialyy.simple.module.DownloadModule;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
@ -58,7 +67,9 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
mStart.setText("开始");
break;
case DOWNLOAD_RESUME:
Toast.makeText(SimpleTestActivity.this, "恢复下载,恢复位置 ==> " + Util.formatFileSize((Long) msg.obj), Toast.LENGTH_SHORT).show();
Toast.makeText(SimpleTestActivity.this,
"恢复下载,恢复位置 ==> " + Util.formatFileSize((Long) msg.obj),
Toast.LENGTH_SHORT).show();
mStart.setEnabled(false);
break;
case DOWNLOAD_COMPLETE:
@ -71,12 +82,27 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
@Override protected void onResume() {
super.onResume();
registerReceiver(mReceiver, getModule(DownloadModule.class).getDownloadFilter());
}
@Override protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
@Override protected int setLayoutId() {
return R.layout.activity_simple;
}
@ -111,58 +137,19 @@ public class SimpleTestActivity extends BaseActivity<ActivitySimpleBinding> {
}
private void start() {
mUtil.download(this, mDownloadUrl, Environment.getExternalStorageDirectory().getPath() + "/test.apk", new DownLoadUtil.DownloadListener() {
long fileSize = 1;
DownloadEntity entity = new DownloadEntity();
entity.setFileName("test.apk");
entity.setDownloadUrl(mDownloadUrl);
entity.setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/test.apk");
List<IDownloadCommand> commands = new ArrayList<>();
IDownloadCommand addCommand = CommandFactory.getInstance()
.createCommand(this, entity, CommandFactory.TASK_CREATE);
IDownloadCommand startCommand = CommandFactory.getInstance()
.createCommand(this, entity, CommandFactory.TASK_START);
commands.add(addCommand);
commands.add(startCommand);
DownloadManager.getInstance(this).setCommands(commands).exe();
@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) {
super.onStart(startLocation);
}
@Override public void onChildResume(long resumeLocation) {
super.onChildResume(resumeLocation);
}
@Override public void onChildComplete(long finishLocation) {
super.onChildComplete(finishLocation);
}
@Override public void onProgress(long currentLocation) {
super.onProgress(currentLocation);
mPb.setProgress((int) (currentLocation * 100 / fileSize));
}
@Override public void onStop(long stopLocation) {
super.onStop(stopLocation);
mUpdateHandler.obtainMessage(DOWNLOAD_STOP).sendToTarget();
}
@Override public void onCancel() {
super.onCancel();
mUpdateHandler.obtainMessage(DOWNLOAD_CANCEL).sendToTarget();
}
@Override public void onResume(long resumeLocation) {
super.onResume(resumeLocation);
mUpdateHandler.obtainMessage(DOWNLOAD_RESUME, resumeLocation).sendToTarget();
}
@Override public void onFail() {
super.onFail();
mUpdateHandler.obtainMessage(DOWNLOAD_FAILE).sendToTarget();
}
@Override public void onComplete() {
super.onComplete();
mUpdateHandler.obtainMessage(DOWNLOAD_COMPLETE).sendToTarget();
}
});
}
private void stop() {

View File

@ -1,21 +1,66 @@
//package com.arialyy.simple.module;
//
//import android.content.Context;
//import com.arialyy.downloadutil.entity.DownloadEntity;
//import com.arialyy.simple.base.BaseModule;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by Lyy on 2016/9/27.
// */
//public class DownloadModule extends BaseModule{
// public DownloadModule(Context context) {
// super(context);
// }
//
// public List<DownloadEntity> getDownloadData(){
// List<DownloadEntity> list = new ArrayList<>();
// DownloadEntity entity
// }
//}
package com.arialyy.simple.module;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Environment;
import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.frame.util.AndroidUtils;
import com.arialyy.frame.util.StringUtil;
import com.arialyy.simple.R;
import com.arialyy.simple.base.BaseModule;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lyy on 2016/9/27.
*/
public class DownloadModule extends BaseModule {
public DownloadModule(Context context) {
super(context);
}
/**
* 设置下载数据
* @return
*/
public List<DownloadEntity> getDownloadData() {
List<DownloadEntity> list = new ArrayList<>();
String[] urls = getContext().getResources()
.getStringArray(R.array.test_apk_download_url);
for (String url : urls) {
String fileName = StringUtil.keyToHashKey(url) + ".apk";
DownloadEntity entity = new DownloadEntity();
entity.setDownloadUrl(url);
entity.setDownloadPath(getDownloadPath(url));
entity.setFileName(fileName);
list.add(entity);
}
return list;
}
/**
* 下载广播过滤器
* @return
*/
public IntentFilter getDownloadFilter(){
IntentFilter filter = new IntentFilter();
filter.addCategory(getContext().getPackageName());
filter.addAction(DownloadManager.ACTION_PRE);
filter.addAction(DownloadManager.ACTION_RESUME);
filter.addAction(DownloadManager.ACTION_START);
filter.addAction(DownloadManager.ACTION_RUNNING);
filter.addAction(DownloadManager.ACTION_STOP);
filter.addAction(DownloadManager.ACTION_CANCEL);
filter.addAction(DownloadManager.ACTION_COMPLETE);
filter.addAction(DownloadManager.ACTION_FAIL);
return filter;
}
private String getDownloadPath(String url) {
return Environment.getExternalStorageDirectory().getPath() + "/" + AndroidUtils.getAppName(
getContext()) + "downloads/" + StringUtil.keyToHashKey(url) + ".apk";
}
}

View File

@ -32,11 +32,13 @@ public class HorizontalProgressBarWithNumber extends ProgressBar {
/**
* offset of draw progress
*/
protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET);
protected int mTextOffset = dp2px(
DEFAULT_SIZE_TEXT_OFFSET);
/**
* height of reached progress bar
*/
protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);
protected int mReachedProgressBarHeight = dp2px(
DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);
/**
* color of reached bar
*/
@ -48,7 +50,8 @@ public class HorizontalProgressBarWithNumber extends ProgressBar {
/**
* height of unreached progress bar
*/
protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);
protected int mUnReachedProgressBarHeight = dp2px(
DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);
/**
* view width except padding
*/
@ -82,7 +85,10 @@ public class HorizontalProgressBarWithNumber extends ProgressBar {
result = specSize;
} else {
float textHeight = (mPaint.descent() - mPaint.ascent());
result = (int) (getPaddingTop() + getPaddingBottom() + Math.max(Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight), Math.abs(textHeight)));
result = (int) (getPaddingTop() + getPaddingBottom() + Math.max(
Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight),
Math.abs(textHeight))
);
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
@ -95,15 +101,28 @@ public class HorizontalProgressBarWithNumber extends ProgressBar {
*/
private void obtainStyledAttributes(AttributeSet attrs) {
// init values from custom attributes
final TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalProgressBarWithNumber);
mTextColor = attributes.getColor(R.styleable.HorizontalProgressBarWithNumber_progress_text_color, DEFAULT_TEXT_COLOR);
mTextSize = (int) attributes.getDimension(R.styleable.HorizontalProgressBarWithNumber_progress_text_size, mTextSize);
mReachedBarColor = attributes.getColor(R.styleable.HorizontalProgressBarWithNumber_progress_reached_color, mTextColor);
mUnReachedBarColor = attributes.getColor(R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color, DEFAULT_COLOR_UNREACHED_COLOR);
mReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height, mReachedProgressBarHeight);
mUnReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height, mUnReachedProgressBarHeight);
mTextOffset = (int) attributes.getDimension(R.styleable.HorizontalProgressBarWithNumber_progress_text_offset, mTextOffset);
int textVisible = attributes.getInt(R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility, VISIBLE);
final TypedArray attributes = getContext().obtainStyledAttributes(attrs,
R.styleable.HorizontalProgressBarWithNumber);
mTextColor = attributes.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_text_color,
DEFAULT_TEXT_COLOR);
mTextSize = (int) attributes.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_text_size, mTextSize);
mReachedBarColor = attributes.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_reached_color, mTextColor);
mUnReachedBarColor = attributes.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color,
DEFAULT_COLOR_UNREACHED_COLOR);
mReachedProgressBarHeight = (int) attributes.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height,
mReachedProgressBarHeight);
mUnReachedProgressBarHeight = (int) attributes.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height,
mUnReachedProgressBarHeight);
mTextOffset = (int) attributes.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_text_offset, mTextOffset);
int textVisible = attributes.getInt(
R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility, VISIBLE);
if (textVisible != VISIBLE) {
mIfDrawText = false;
}
@ -151,13 +170,15 @@ public class HorizontalProgressBarWithNumber extends ProgressBar {
* dp 2 px
*/
protected int dp2px(int dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal,
getResources().getDisplayMetrics());
}
/**
* sp 2 px
*/
protected int sp2px(int spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal,
getResources().getDisplayMetrics());
}
}

View File

@ -1,16 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HorizontalProgressBarWithNumber">
<attr name="progress_unreached_color" format="color" />
<attr name="progress_reached_color" format="color" />
<attr name="progress_reached_bar_height" format="dimension" />
<attr name="progress_unreached_bar_height" format="dimension" />
<attr name="progress_text_size" format="dimension" />
<attr name="progress_text_color" format="color" />
<attr name="progress_text_offset" format="dimension" />
<attr name="progress_unreached_color" format="color"/>
<attr name="progress_reached_color" format="color"/>
<attr name="progress_reached_bar_height" format="dimension"/>
<attr name="progress_unreached_bar_height" format="dimension"/>
<attr name="progress_text_size" format="dimension"/>
<attr name="progress_text_color" format="color"/>
<attr name="progress_text_offset" format="dimension"/>
<attr name="progress_text_visibility" format="enum">
<enum name="visible" value="0" />
<enum name="invisible" value="1" />
<enum name="visible" value="0"/>
<enum name="invisible" value="1"/>
</attr>
</declare-styleable>
</resources>

View File

@ -1,4 +1,18 @@
<resources>
<string name="app_name">DownloadDemo</string>
<string name="action_settings">Settings</string>
<string-array name="test_apk_download_url">
<item>http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk</item> <!--300M的文件-->
<item>http://static.gaoshouyou.com/d/21/e8/61218d78d0e8b79df68dbc18dd484c97.apk</item>
<item>http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk</item>
<item>http://static.gaoshouyou.com/d/d4/4f/d6d48db3794fb9ecf47e83c346570881.apk</item>
<!--<item>http://static.gaoshouyou.com/d/18/cf/ba18113bc6cf56c1c5863e761e717003.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/60/17/2460921367173ea7145f11194a6f2587.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/32/e0/1a32123ecbe0ee010d35479df248f90f.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/e6/f5/4de6329f9cf5dc3a1d1e6bbcca0d003c.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/6e/e5/ff6ecaaf45e532e6d07747af82357472.apk</item>-->
<!--<item>http://static.gaoshouyou.com/d/36/69/2d3699acfa69e9632262442c46516ad8.apk</item>-->
</string-array>
</resources>

View File

@ -1,7 +1,9 @@
package com.arialyy.downloadutil.core;
import android.content.Context;
import com.arialyy.downloadutil.core.command.IDownloadCommand;
import java.util.ArrayList;
import java.util.List;
@ -93,10 +95,11 @@ public class DownloadManager {
/**
* 设置一组命令
*/
public void setCommands(List<IDownloadCommand> commands) {
public DownloadManager setCommands(List<IDownloadCommand> commands) {
if (commands != null && commands.size() > 0) {
mCommands.addAll(commands);
}
return this;
}
/**

View File

@ -2,6 +2,7 @@ package com.arialyy.downloadutil.core;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity;
/**
@ -87,12 +88,18 @@ public class DownloadTarget extends IDownloadTarget {
@Override public void removeTask(DownloadEntity entity) {
Task task = mCachePool.getTask(entity.getDownloadUrl());
if (task != null) {
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ? "成功" : "失败"));
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ?
"成功" :
"失败"
));
} else {
task = mExecutePool.getTask(entity.getDownloadUrl());
}
if (task != null) {
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ? "成功" : "失败"));
Log.d(TAG, "任务删除" + (mCachePool.removeTask(task) ?
"成功" :
"失败"
));
} else {
Log.w(TAG, "没有找到下载链接为【" + entity.getDownloadUrl() + "】的任务");
}

View File

@ -3,6 +3,7 @@ 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;

View File

@ -4,9 +4,11 @@ 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.DownLoadUtil;
import com.arialyy.downloadutil.util.IDownloadListener;
import java.net.HttpURLConnection;
/**
@ -36,8 +38,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);
}
}
@ -79,7 +81,8 @@ public class Task {
long lastLen = 0; //上一次发送长度
DownloadEntity downloadEntity;
public DownloadListener(Context context, DownloadEntity downloadEntity, Handler outHandler) {
public DownloadListener(Context context, DownloadEntity downloadEntity,
Handler outHandler) {
this.context = context;
this.outHandler = outHandler;
this.downloadEntity = downloadEntity;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,9 +2,11 @@ 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;
@ -47,7 +49,10 @@ public class CachePool implements IPool {
return false;
} else {
boolean s = mCacheQueue.offer(task);
Log.w(TAG, "任务添加" + (s ? "成功" : "失败,【" + url + ""));
Log.w(TAG, "任务添加" + (s ?
"成功" :
"失败,【" + url + ""
));
if (s) {
mCacheArray.put(Util.keyToHashKey(url), task);
}

View File

@ -2,9 +2,11 @@ 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;
@ -68,7 +70,10 @@ public class ExecutePool implements IPool {
private boolean putNewTask(Task newTask) {
String url = newTask.getDownloadEntity().getDownloadUrl();
boolean s = mExecuteQueue.offer(newTask);
Log.w(TAG, "任务添加" + (s ? "成功" : "失败,【" + url + ""));
Log.w(TAG, "任务添加" + (s ?
"成功" :
"失败,【" + url + ""
));
if (s) {
newTask.start();
mExecuteArray.put(Util.keyToHashKey(url), newTask);

View File

@ -2,6 +2,7 @@ package com.arialyy.downloadutil.entity;
import android.os.Parcel;
import android.os.Parcelable;
import com.arialyy.downloadutil.orm.DbEntity;
/**
@ -146,7 +147,9 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
dest.writeLong(this.completeTime);
dest.writeLong(this.fileSize);
dest.writeInt(this.state);
dest.writeByte(this.isDownloadComplete ? (byte) 1 : (byte) 0);
dest.writeByte(this.isDownloadComplete ?
(byte) 1 :
(byte) 0);
dest.writeLong(this.currentProgress);
dest.writeInt(this.failNum);
}

View File

@ -3,8 +3,10 @@ package com.arialyy.downloadutil.help;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.downloadutil.R;
import com.arialyy.downloadutil.entity.DownloadEntity;
import java.io.File;
/**
@ -31,7 +33,7 @@ public class CheckHelp {
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
return false;
} else if (TextUtils.isEmpty(entity.getDownloadPath())) {
Log.w(TAG, Resources.getSystem().getString(R.string.error_file_name_null));
Log.w(TAG, Resources.getSystem().getString(R.string.error_download_path_null));
return false;
}
String fileName = entity.getFileName();

View File

@ -0,0 +1,63 @@
package com.arialyy.downloadutil.help;
import android.os.Environment;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by lyy on 2016/9/27.
* 下载路径帮助类
*/
public class PathHelp {
/**
* 下载链接转换保存路径
*
* @param downloadUrl 下载链接
* @return 保存路径
*/
public static String urlconvertPath(String downloadUrl) {
return Environment.getDownloadCacheDirectory().getPath() + "/" + StringToHashKey(
downloadUrl);
}
/**
* 字符串转换为hash码
*
* @param str
* @return
*/
public static String StringToHashKey(String str) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(str.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(str.hashCode());
}
return cacheKey;
}
/**
* 将普通字符串转换为16位进制字符串
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("0x");
if (src == null || src.length <= 0) {
return null;
}
char[] buffer = new char[2];
for (byte aSrc : src) {
buffer[0] = Character.forDigit((aSrc >>> 4) & 0x0F, 16);
buffer[1] = Character.forDigit(aSrc & 0x0F, 16);
stringBuilder.append(buffer);
}
return stringBuilder.toString();
}
}

View File

@ -4,7 +4,9 @@ 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;
@ -77,7 +79,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});
}
/**
@ -108,7 +110,9 @@ public class DbEntity {
*/
public <T extends DbEntity> List<T> findAllData(Class<T> clazz) {
Cursor cursor = mUtil.findAllData(this);
return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
return cursor.getCount() > 0 ?
newInstanceEntity(clazz, cursor) :
null;
}
/**
@ -119,7 +123,9 @@ public class DbEntity {
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;
return cursor.getCount() > 0 ?
newInstanceEntity(clazz, cursor) :
null;
}
/**
@ -130,7 +136,9 @@ public class DbEntity {
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;
return cursor.getCount() > 0 ?
newInstanceEntity(clazz, cursor).get(0) :
null;
}
/**
@ -142,8 +150,10 @@ 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) {
@ -165,7 +175,8 @@ public class DbEntity {
} else if (type == long.class || type == Long.class) {
field.setLong(entity, cursor.getLong(column));
} else if (type == boolean.class || type == Boolean.class) {
field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false"));
field.setBoolean(entity,
!cursor.getString(column).equalsIgnoreCase("false"));
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
field.set(entity, new Date(cursor.getString(column)));
} else if (type == byte[].class) {

View File

@ -4,7 +4,9 @@ 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;
/**
@ -60,7 +62,9 @@ public class DbUtil {
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ",");
sb.append(i >= wheres.length - 1 ?
"" :
",");
i++;
}
print(DEL_DATA, sb.toString());
@ -83,7 +87,9 @@ public class DbUtil {
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(i > 0 ?
", " :
"");
try {
sb.append(field.getName())
.append(" = '")
@ -112,7 +118,8 @@ public class DbUtil {
/**
* 条件查寻数据
*/
protected Cursor findData(DbEntity dbEntity, @NonNull Object[] wheres, @NonNull Object[] values) {
protected Cursor findData(DbEntity dbEntity, @NonNull Object[] wheres,
@NonNull Object[] values) {
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "请输入查询条件");
return null;
@ -125,7 +132,9 @@ public class DbUtil {
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ", ");
sb.append(i >= wheres.length - 1 ?
"" :
", ");
i++;
}
print(FIND_DATA, sb.toString());
@ -148,7 +157,9 @@ public class DbUtil {
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(i > 0 ?
", " :
"");
sb.append(field.getName());
i++;
}
@ -160,7 +171,9 @@ public class DbUtil {
if (ignore != null && ignore.value()) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(i > 0 ?
", " :
"");
sb.append("'");
try {
sb.append(field.get(dbEntity)).append("'");
@ -238,7 +251,9 @@ public class DbUtil {
} else {
sb.append(" blob");
}
sb.append(i >= fields.length - ignoreNum - 1 ? "" : ", ");
sb.append(i >= fields.length - ignoreNum - 1 ?
"" :
", ");
}
sb.append(");");
print(CREATE_TABLE, sb.toString());
@ -310,7 +325,9 @@ public class DbUtil {
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ",");
sb.append(i >= wheres.length - 1 ?
"" :
",");
i++;
}
print(ROW_ID, sb.toString());

View File

@ -4,6 +4,7 @@ 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;
@ -79,7 +80,8 @@ public class DownLoadUtil {
* @param downloadListener 下载进度监听 {@link DownloadListener}
*/
public void download(final Context context, @NonNull final String downloadUrl,
@NonNull final String filePath, @NonNull final IDownloadListener downloadListener) {
@NonNull final String filePath,
@NonNull final IDownloadListener downloadListener) {
isDownloading = true;
mCurrentLocation = 0;
isStop = false;
@ -88,8 +90,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;
@ -175,9 +177,8 @@ 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 + "_恢复下载 ++++++++++");
@ -195,8 +196,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));
}
@ -216,12 +217,9 @@ 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();
@ -245,23 +243,15 @@ public class DownLoadUtil {
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() {
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();
//在头里面请求下载开始位置和结束位置
@ -328,7 +318,8 @@ public class DownLoadUtil {
String location = String.valueOf(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) {
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
isDownloading = false;
@ -357,7 +348,8 @@ public class DownLoadUtil {
synchronized (DownLoadUtil.this) {
try {
String location = String.valueOf(currentLocation);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId, location);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId,
location);
failDownload("下载链接异常");
} catch (IOException e1) {
e1.printStackTrace();
@ -367,8 +359,10 @@ public class DownLoadUtil {
synchronized (DownLoadUtil.this) {
try {
String location = String.valueOf(currentLocation);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId, location);
failDownload("下载失败【" + dEntity.downloadUrl + "" + Util.getPrintException(e));
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId,
location);
failDownload(
"下载失败【" + dEntity.downloadUrl + "" + Util.getPrintException(e));
} catch (IOException e1) {
e1.printStackTrace();
}
@ -377,7 +371,8 @@ public class DownLoadUtil {
synchronized (DownLoadUtil.this) {
try {
String location = String.valueOf(currentLocation);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId, location);
writeConfig(dEntity.tempFile.getName() + "_record_" + dEntity.threadId,
location);
failDownload("获取流失败" + Util.getPrintException(e));
} catch (IOException e1) {
e1.printStackTrace();

View File

@ -1,6 +1,7 @@
package com.arialyy.downloadutil.util;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;