pull/2/head
lyy 9 years ago
parent 08d662e053
commit a52338c5d3
  1. 7
      app/src/main/java/com/arialyy/simple/activity/MultiTaskActivity.java
  2. 2
      app/src/main/java/com/arialyy/simple/activity/SingleTaskActivity.java
  3. 73
      app/src/main/java/com/arialyy/simple/adapter/DownloadAdapter.java
  4. 12
      app/src/main/java/com/arialyy/simple/module/DownloadModule.java
  5. 5
      app/src/main/res/color/bt_selector_cancel.xml
  6. 35
      app/src/main/res/layout/item_download.xml
  7. 1
      app/src/main/res/values/colors.xml
  8. 48
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownLoadUtil.java
  9. 61
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadEntity.java
  10. 6
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadManager.java
  11. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/DownloadTarget.java
  12. 6
      downloadutil/src/main/java/com/arialyy/downloadutil/core/IDownloadListener.java
  13. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/IDownloadTarget.java
  14. 44
      downloadutil/src/main/java/com/arialyy/downloadutil/core/Task.java
  15. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/TaskFactory.java
  16. 4
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/AddCommand.java
  17. 4
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/CancelCommand.java
  18. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/CommandFactory.java
  19. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/IDownloadCommand.java
  20. 4
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StartCommand.java
  21. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StateCommand.java
  22. 4
      downloadutil/src/main/java/com/arialyy/downloadutil/core/command/StopCommand.java
  23. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/inf/IDownloader.java
  24. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/inf/IPool.java
  25. 6
      downloadutil/src/main/java/com/arialyy/downloadutil/core/inf/ITask.java
  26. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/pool/CachePool.java
  27. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/core/pool/ExecutePool.java
  28. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/help/CheckHelp.java
  29. 2
      downloadutil/src/main/java/com/arialyy/downloadutil/orm/DbEntity.java
  30. 163
      downloadutil/src/main/java/com/arialyy/downloadutil/util/SQLHelper.java
  31. 11
      downloadutil/src/main/java/com/arialyy/downloadutil/util/Util.java

@ -8,8 +8,8 @@ import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import butterknife.Bind;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.frame.util.show.L;
import com.arialyy.simple.R;
import com.arialyy.simple.adapter.DownloadAdapter;
@ -59,7 +59,9 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
break;
case DownloadManager.ACTION_RUNNING:
long current = intent.getLongExtra(DownloadManager.CURRENT_LOCATION, 0);
mAdapter.setProgress(entity.getDownloadUrl(), current);
long speed = intent.getLongExtra(DownloadManager.CURRENT_SPEED, 0);
//mAdapter.setProgress(entity.getDownloadUrl(), current, speed);
mAdapter.setProgress(entity);
break;
case DownloadManager.ACTION_STOP:
L.d(TAG, "download stop");
@ -71,6 +73,7 @@ public class MultiTaskActivity extends BaseActivity<ActivityMultiBinding> {
break;
case DownloadManager.ACTION_CANCEL:
L.d(TAG, "download cancel");
mAdapter.updateState(entity);
break;
case DownloadManager.ACTION_FAIL:
L.d(TAG, "download fail");

@ -17,7 +17,7 @@ import butterknife.Bind;
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.core.DownloadEntity;
import com.arialyy.downloadutil.orm.DbEntity;
import com.arialyy.downloadutil.util.Util;
import com.arialyy.frame.util.show.L;

@ -4,14 +4,15 @@ import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.Bind;
import com.arialyy.absadapter.common.AbsHolder;
import com.arialyy.absadapter.recycler_view.AbsRVAdapter;
import com.arialyy.downloadutil.core.DownloadEntity;
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.frame.util.show.L;
import com.arialyy.downloadutil.util.Util;
import com.arialyy.simple.R;
import com.arialyy.simple.widget.HorizontalProgressBarWithNumber;
import java.util.ArrayList;
@ -28,14 +29,12 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
private static final String TAG = "DownloadAdapter";
private DownloadManager mManager;
private CommandFactory mFactory;
private Map<String, Long> mProgress = new HashMap<>();
private Map<String, Integer> mPositions = new HashMap<>();
public DownloadAdapter(Context context, List<DownloadEntity> data) {
super(context, data);
int i = 0;
for (DownloadEntity entity : data) {
mProgress.put(entity.getDownloadUrl(), entity.getCurrentProgress());
mPositions.put(entity.getDownloadUrl(), i);
i++;
}
@ -52,15 +51,26 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
}
public synchronized void updateState(DownloadEntity entity) {
notifyItemChanged(indexItem(entity.getDownloadUrl()));
if (entity.getState() == DownloadEntity.STATE_CANCEL) {
mPositions.clear();
int i = 0;
for (DownloadEntity entity_1 : mData) {
mPositions.put(entity_1.getDownloadUrl(), i);
i++;
}
notifyDataSetChanged();
} else {
int position = indexItem(entity.getDownloadUrl());
mData.set(position, entity);
notifyItemChanged(position);
}
}
public synchronized void setProgress(String url, long currentPosition) {
mProgress.put(url, currentPosition);
// int index = indexItem(url);
// L.d(TAG, "index ==> " + index);
// notifyItemChanged(index);
notifyItemChanged(indexItem(url));
public synchronized void setProgress(DownloadEntity entity) {
String url = entity.getDownloadUrl();
int position = indexItem(url);
mData.set(position, entity);
notifyItemChanged(position);
}
private synchronized int indexItem(String url) {
@ -74,14 +84,12 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
return -1;
}
@Override protected void bindData(MyHolder holder, int position, DownloadEntity item) {
//holder.progress.setProgress(item.getCurrentProgress());
long size = item.getFileSize();
int current = 0;
if (size == 0) {
current = 0;
}
current = (int) (mProgress.get(item.getDownloadUrl()) * 100 / item.getFileSize());
@Override protected void bindData(MyHolder holder, int position, final DownloadEntity item) {
long size = item.getFileSize();
int current = 0;
long progress = item.getCurrentProgress();
long speed = item.getSpeed();
current = size == 0 ? 0 : (int) (progress * 100 / size);
holder.progress.setProgress(current);
BtClickListener listener = new BtClickListener(position, item);
holder.bt.setOnClickListener(listener);
@ -108,6 +116,22 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
}
holder.bt.setText(str);
holder.bt.setTextColor(getColor(color));
holder.speed.setText(Util.formatFileSize(speed) + "/s");
holder.fileSize.setText(covertCurrentSize(progress) + "/" + Util.formatFileSize(size));
holder.cancel.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
mData.remove(item);
notifyDataSetChanged();
IDownloadCommand cancelCommand =
mFactory.createCommand(getContext(), item, CommandFactory.TASK_CANCEL);
mManager.setCommand(cancelCommand).exe();
}
});
}
private String covertCurrentSize(long currentSize) {
String size = Util.formatFileSize(currentSize);
return size.substring(0, size.length() - 1);
}
private int getColor(int color) {
@ -124,7 +148,6 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
}
@Override public void onClick(View v) {
L.d(TAG, "position ==> " + position);
switch (entity.getState()) {
case DownloadEntity.STATE_WAIT:
case DownloadEntity.STATE_OTHER:
@ -140,7 +163,6 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
}
private void start(DownloadEntity entity) {
List<IDownloadCommand> commands = new ArrayList<>();
IDownloadCommand addCommand =
mFactory.createCommand(getContext(), entity, CommandFactory.TASK_CREATE);
@ -156,17 +178,14 @@ public class DownloadAdapter extends AbsRVAdapter<DownloadEntity, DownloadAdapte
mFactory.createCommand(getContext(), entity, CommandFactory.TASK_STOP);
mManager.setCommand(stopCommand).exe();
}
private void cancel(DownloadEntity entity) {
IDownloadCommand cancelCommand =
mFactory.createCommand(getContext(), entity, CommandFactory.TASK_CANCEL);
mManager.setCommand(cancelCommand).exe();
}
}
class MyHolder extends AbsHolder {
@Bind(R.id.progressBar) HorizontalProgressBarWithNumber progress;
@Bind(R.id.bt) Button bt;
@Bind(R.id.speed) TextView speed;
@Bind(R.id.fileSize) TextView fileSize;
@Bind(R.id.del) TextView cancel;
MyHolder(View itemView) {
super(itemView);

@ -4,7 +4,7 @@ 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.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.util.Util;
import com.arialyy.frame.util.AndroidUtils;
import com.arialyy.frame.util.StringUtil;
@ -27,11 +27,8 @@ public class DownloadModule extends BaseModule {
*/
public List<DownloadEntity> getDownloadData() {
List<DownloadEntity> list = DownloadEntity.findAllData(DownloadEntity.class);
List<DownloadEntity> newDownload = createNewDownload();
if (list == null) {
list = newDownload;
} else {
list = filter(list, newDownload);
if (list == null || list.size() == 0) {
list = createNewDownload();
}
return list;
}
@ -53,7 +50,7 @@ public class DownloadModule extends BaseModule {
break;
}
count++;
if (count == sqlEntity.size()) {
if (count == createdEntity.size()) {
list.add(cEntity);
}
}
@ -74,6 +71,7 @@ public class DownloadModule extends BaseModule {
entity.setDownloadUrl(url);
entity.setDownloadPath(getDownloadPath(url));
entity.setFileName(fileName);
entity.save();
list.add(entity);
}
return list;

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/black" android:state_pressed="true"/>
<item android:color="@color/colorAccent" android:state_pressed="false"/>
</selector>

@ -9,19 +9,50 @@
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:layout_toLeftOf="@+id/bt"
android:max="100"
/>
<TextView
android:id="@+id/fileSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar"
android:layout_marginTop="8dp"
android:text="0mb/0mb"
android:textColor="@color/black"
/>
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="开始"
style="?buttonBarButtonStyle"
/>
<TextView
android:id="@+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/fileSize"
android:layout_centerHorizontal="true"
android:text="0kb/s"
android:textColor="@color/black"
/>
<TextView
android:id="@+id/del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/progressBar"
android:layout_alignTop="@+id/fileSize"
android:text="删除"
android:textColor="@color/bt_selector_cancel"
/>
</RelativeLayout>

@ -3,4 +3,5 @@
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="black">#2B2B2B</color>
</resources>

@ -1,16 +1,17 @@
package com.arialyy.downloadutil.util;
package com.arialyy.downloadutil.core;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.SparseArray;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
@ -71,10 +72,14 @@ final class DownLoadUtil {
*/
public void cancelDownload() {
isCancel = true;
Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++");
isDownloading = false;
mFixedThreadPool.shutdown();
mListener.onCancel();
for (int i = 0; i < THREAD_NUM; i++) {
DownLoadTask task = (DownLoadTask) mTask.get(i);
if (task != null) {
task.cancel();
}
}
}
/**
@ -82,7 +87,6 @@ final class DownLoadUtil {
*/
public void stopDownload() {
isStop = true;
Log.d(TAG, "++++++++++++++++ onStop +++++++++++++++++");
isDownloading = false;
mFixedThreadPool.shutdown();
for (int i = 0; i < THREAD_NUM; i++) {
@ -155,13 +159,8 @@ final class DownLoadUtil {
mListener = downloadListener;
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
setCommadParam(conn);
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.connect();
int len = conn.getContentLength();
if (len < 0) { //网络被劫持时会出现这个问题
@ -177,7 +176,7 @@ final class DownLoadUtil {
RandomAccessFile file = new RandomAccessFile(filePath, "rwd");
//设置文件长度
file.setLength(fileLength);
mListener.onPreDownload(conn);
mListener.onPreDownload(conn.getContentLength());
//分配每条线程的下载区间
Properties pro = null;
pro = Util.loadConfig(configFile);
@ -282,9 +281,17 @@ final class DownLoadUtil {
mListener.onFail();
}
private void setCommadParam(HttpURLConnection conn) throws ProtocolException {
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
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, */*");
}
/**
* 多线程下载任务类,不能使用AsyncTask来进行多线程下载因为AsyncTask是串行执行的这种方式下载速度太慢了
* 单个线程的下载任务
*/
private class DownLoadTask implements Runnable {
private static final String TAG = "DownLoadTask";
@ -316,12 +323,7 @@ final class DownLoadUtil {
//在头里面请求下载开始位置和结束位置
conn.setRequestProperty("Range",
"bytes=" + dEntity.startLocation + "-" + dEntity.endLocation);
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
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, */*");
setCommadParam(conn);
conn.setConnectTimeout(TIME_OUT * 4);
conn.setReadTimeout(TIME_OUT * 24); //设置读取流的等待时间,必须设置该参数
is = conn.getInputStream();
@ -416,9 +418,9 @@ final class DownLoadUtil {
if (dEntity.tempFile.exists()) {
dEntity.tempFile.delete();
}
//Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++");
//isDownloading = false;
//mListener.onCancel();
Log.d(TAG, "++++++++++++++++ onCancel +++++++++++++++++");
isDownloading = false;
mListener.onCancel();
}
}
}
@ -504,7 +506,7 @@ final class DownLoadUtil {
}
@Override public void onPreDownload(HttpURLConnection connection) {
@Override public void onPreDownload(long fileSize) {
}

@ -1,4 +1,4 @@
package com.arialyy.downloadutil.entity;
package com.arialyy.downloadutil.core;
import android.os.Parcel;
import android.os.Parcelable;
@ -39,16 +39,17 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
*/
@Ignore public static final int STATE_CANCEL = 5;
private String downloadUrl = ""; //下载路径
private String downloadPath = ""; //保存路径
private String fileName = ""; //文件名
private String str = ""; //其它字段
@Ignore private long speed = 0; //下载速度
private String downloadUrl = ""; //下载路径
private String downloadPath = ""; //保存路径
private String fileName = ""; //文件名
private String str = ""; //其它字段
private long fileSize = 1;
private int state = STATE_WAIT;
private boolean isDownloadComplete = false; //是否下载完成
private long currentProgress = 0; //当前下载进度
private int failNum = 0;
private long completeTime; //完成时间
private long fileSize = 1;
private int state = STATE_WAIT;
private boolean isDownloadComplete = false; //是否下载完成
private long currentProgress = 0; //当前下载进度
private int failNum = 0;
public DownloadEntity() {
}
@ -125,6 +126,14 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
isDownloadComplete = downloadComplete;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public long getCurrentProgress() {
return currentProgress;
}
@ -137,6 +146,19 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
return (DownloadEntity) super.clone();
}
@Override public String toString() {
return "DownloadEntity{" +
"downloadUrl='" + downloadUrl + '\'' +
", downloadPath='" + downloadPath + '\'' +
", completeTime=" + completeTime +
", fileSize=" + fileSize +
", state=" + state +
", isDownloadComplete=" + isDownloadComplete +
", currentProgress=" + currentProgress +
", failNum=" + failNum +
'}';
}
@Override public int describeContents() {
return 0;
}
@ -144,23 +166,29 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.downloadUrl);
dest.writeString(this.downloadPath);
dest.writeString(this.fileName);
dest.writeString(this.str);
dest.writeLong(this.completeTime);
dest.writeLong(this.fileSize);
dest.writeInt(this.state);
dest.writeByte(this.isDownloadComplete ? (byte) 1 : (byte) 0);
dest.writeLong(this.currentProgress);
dest.writeInt(this.failNum);
dest.writeLong(this.speed);
}
protected DownloadEntity(Parcel in) {
this.downloadUrl = in.readString();
this.downloadPath = in.readString();
this.fileName = in.readString();
this.str = in.readString();
this.completeTime = in.readLong();
this.fileSize = in.readLong();
this.state = in.readInt();
this.isDownloadComplete = in.readByte() != 0;
this.currentProgress = in.readLong();
this.failNum = in.readInt();
this.speed = in.readLong();
}
@Ignore public static final Creator<DownloadEntity> CREATOR = new Creator<DownloadEntity>() {
@ -172,17 +200,4 @@ public class DownloadEntity extends DbEntity implements Parcelable, Cloneable {
return new DownloadEntity[size];
}
};
@Override public String toString() {
return "DownloadEntity{" +
"downloadUrl='" + downloadUrl + '\'' +
", downloadPath='" + downloadPath + '\'' +
", completeTime=" + completeTime +
", fileSize=" + fileSize +
", state=" + state +
", isDownloadComplete=" + isDownloadComplete +
", currentProgress=" + currentProgress +
", failNum=" + failNum +
'}';
}
}

@ -4,7 +4,6 @@ import android.app.Application;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.core.command.IDownloadCommand;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.orm.DbEntity;
import com.arialyy.downloadutil.orm.DbUtil;
import java.util.ArrayList;
@ -68,6 +67,11 @@ public class DownloadManager {
*/
public static final String CURRENT_LOCATION = "CURRENT_LOCATION";
/**
* 速度
*/
public static final String CURRENT_SPEED = "CURRENT_SPEED";
private List<IDownloadCommand> mCommands = new ArrayList<>();
private DownloadManager() {

@ -2,8 +2,6 @@ package com.arialyy.downloadutil.core;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/**
* Created by lyy on 2016/8/17.

@ -1,6 +1,4 @@
package com.arialyy.downloadutil.util;
import java.net.HttpURLConnection;
package com.arialyy.downloadutil.core;
/**
* 下载监听
@ -19,7 +17,7 @@ public interface IDownloadListener {
/**
* 下载预处理,可通过HttpURLConnection获取文件长度
*/
public void onPreDownload(HttpURLConnection connection);
public void onPreDownload(long fileSize);
/**
* 下载监听

@ -7,8 +7,6 @@ import com.arialyy.downloadutil.core.inf.IDownloader;
import com.arialyy.downloadutil.core.inf.ITask;
import com.arialyy.downloadutil.core.pool.CachePool;
import com.arialyy.downloadutil.core.pool.ExecutePool;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/**
* Created by lyy on 2016/8/16.

@ -1,14 +1,10 @@
package com.arialyy.downloadutil.util;
package com.arialyy.downloadutil.core;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import com.arialyy.downloadutil.core.DownloadManager;
import com.arialyy.downloadutil.core.IDownloadTarget;
import com.arialyy.downloadutil.entity.DownloadEntity;
import java.net.HttpURLConnection;
/**
* Created by lyy on 2016/8/11.
@ -131,10 +127,11 @@ public class Task {
Handler outHandler;
Context context;
Intent sendIntent;
long INTERVAL = 1024 * 10; //10k大小的间隔
long lastLen = 0; //上一次发送长度
long lastTime = 0;
long INTERVAL_TIME = 60 * 1000; //10k大小的间隔
long INTERVAL = 1024 * 10; //10k大小的间隔
long lastLen = 0; //上一次发送长度
long lastTime = 0;
long INTERVAL_TIME = 1000; //1m更新周期
boolean isFirst = true;
DownloadEntity downloadEntity;
DownloadListener(Context context, DownloadEntity downloadEntity, Handler outHandler) {
@ -145,10 +142,9 @@ public class Task {
sendIntent.putExtra(DownloadManager.ENTITY, downloadEntity);
}
@Override public void onPreDownload(HttpURLConnection connection) {
super.onPreDownload(connection);
long len = connection.getContentLength();
downloadEntity.setFileSize(len);
@Override public void onPreDownload(long fileSize) {
super.onPreDownload(fileSize);
downloadEntity.setFileSize(fileSize);
downloadEntity.setState(DownloadEntity.STATE_DOWNLOAD_ING);
sendIntent(DownloadManager.ACTION_PRE, -1);
}
@ -168,14 +164,19 @@ public class Task {
@Override public void onProgress(long currentLocation) {
super.onProgress(currentLocation);
// if (currentLocation - lastLen > INTERVAL) { //不要太过于频繁发送广播
// sendIntent.putExtra(DownloadManager.CURRENT_LOCATION, currentLocation);
// lastLen = currentLocation;
// context.sendBroadcast(sendIntent);
// }
if (System.currentTimeMillis() - lastLen > INTERVAL_TIME) {
if (System.currentTimeMillis() - lastTime > INTERVAL_TIME) {
long speed = currentLocation - lastLen;
sendIntent.putExtra(DownloadManager.CURRENT_LOCATION, currentLocation);
sendIntent.putExtra(DownloadManager.CURRENT_SPEED, speed);
lastTime = System.currentTimeMillis();
if (isFirst) {
downloadEntity.setSpeed(0);
isFirst = false;
} else {
downloadEntity.setSpeed(speed);
}
downloadEntity.setCurrentProgress(currentLocation);
lastLen = currentLocation;
context.sendBroadcast(sendIntent);
}
}
@ -183,6 +184,7 @@ public class Task {
@Override public void onStop(long stopLocation) {
super.onStop(stopLocation);
downloadEntity.setState(DownloadEntity.STATE_STOP);
downloadEntity.setSpeed(0);
sendInState2Target(IDownloadTarget.STOP);
sendIntent(DownloadManager.ACTION_STOP, stopLocation);
}
@ -199,13 +201,15 @@ public class Task {
super.onComplete();
downloadEntity.setState(DownloadEntity.STATE_COMPLETE);
downloadEntity.setDownloadComplete(true);
downloadEntity.setSpeed(0);
sendInState2Target(IDownloadTarget.COMPLETE);
sendIntent(DownloadManager.ACTION_COMPLETE, -1);
sendIntent(DownloadManager.ACTION_COMPLETE, downloadEntity.getFileSize());
}
@Override public void onFail() {
super.onFail();
downloadEntity.setState(DownloadEntity.STATE_FAIL);
downloadEntity.setSpeed(0);
sendInState2Target(IDownloadTarget.FAIL);
sendIntent(DownloadManager.ACTION_FAIL, -1);
}

@ -2,8 +2,6 @@ package com.arialyy.downloadutil.core;
import android.content.Context;
import android.os.Handler;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
/**
* Created by lyy on 2016/8/18.

@ -2,8 +2,8 @@ package com.arialyy.downloadutil.core.command;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/22.

@ -1,8 +1,8 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/9/20.

@ -1,7 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.core.DownloadEntity;
/**
* Created by Lyy on 2016/9/23.

@ -3,7 +3,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;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.help.CheckHelp;
import com.arialyy.downloadutil.util.Util;

@ -1,8 +1,8 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/22.

@ -1,7 +1,7 @@
package com.arialyy.downloadutil.core.command;
import android.content.Context;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.core.DownloadEntity;
/**
* Created by lyy on 2016/9/20.

@ -2,8 +2,8 @@ package com.arialyy.downloadutil.core.command;
import android.content.Context;
import android.util.Log;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/9/20.

@ -1,6 +1,6 @@
package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/16.

@ -1,6 +1,6 @@
package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/14.

@ -1,7 +1,7 @@
package com.arialyy.downloadutil.core.inf;
import com.arialyy.downloadutil.entity.DownloadEntity;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.DownloadEntity;
import com.arialyy.downloadutil.core.Task;
/**
* Created by lyy on 2016/8/16.
@ -29,7 +29,7 @@ public interface ITask {
* 通过下载链接搜索下载任务
*
* @param entity 下载实体{@link DownloadEntity}
* @return {@code -1 ==> 错误}{@link com.arialyy.downloadutil.entity.DownloadEntity#STATE_FAIL}
* @return {@code -1 ==> 错误}{@link DownloadEntity#STATE_FAIL}
*/
public int getTaskState(DownloadEntity entity);

@ -3,7 +3,7 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.Task;
import com.arialyy.downloadutil.util.Util;
import java.util.HashMap;
import java.util.Map;

@ -3,7 +3,7 @@ package com.arialyy.downloadutil.core.pool;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.downloadutil.core.inf.IPool;
import com.arialyy.downloadutil.util.Task;
import com.arialyy.downloadutil.core.Task;
import com.arialyy.downloadutil.util.Util;
import java.util.HashMap;
import java.util.Map;

@ -4,7 +4,7 @@ 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 com.arialyy.downloadutil.core.DownloadEntity;
import java.io.File;
/**

@ -56,7 +56,7 @@ public class DbEntity {
/**
* 保存自身如果表中已经有数据则更新数据否则插入数据
*/
public void save() {
public synchronized void save() {
if (mUtil.tableExists(getClass()) && thisIsExist()) {
update();
} else {

@ -1,163 +0,0 @@
//package com.arialyy.downloadutil.util;
//
//import android.content.ContentValues;
//import android.content.Context;
//import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteOpenHelper;
//import android.support.annotation.NonNull;
//
//import com.arialyy.downloadutil.entity.ConfigEntity;
//
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by lyy on 2016/8/11.
// * 数据库帮助类
// */
//public class SQLHelper extends SQLiteOpenHelper {
// public static final String DB_NAME = "ARIA_LYY_DB";
// public static final String TABLE_NAME = "ARIA_LYY_DOWNLOAD";
//
// public SQLHelper(Context context) {
// this(context, DB_NAME, null, 1);
// }
//
// private SQLHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// String sql = "create table " + TABLE_NAME + "(" +
// "url varchar PRIMARY KEY, " +
// "path varchar, " +
// "completeTime interger, " +
// "fileSize interger, " +
// "state smallint , " +
// "isDownloadComplete smallint, " +
// "currentProgress interger" +
// ")";
// db.execSQL(sql);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
// }
//
// /**
// * 获取所有下载实体
// */
// public List<ConfigEntity> getAllEntity(@NonNull SQLiteDatabase db) {
// List<ConfigEntity> list = new ArrayList<>();
// Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null);
// if (c.moveToFirst()) {
// while (c.moveToNext()) {
// list.insert(cursor2Entity(c));
// }
// }
// c.close();
// return list;
// }
//
// /**
// * 更新下载实体
// */
// public void updateEntity(@NonNull SQLiteDatabase db, ConfigEntity entity) {
// String whereClause = "url=?";
// String[] whereArgs = {entity.getDownloadUrl()};
// db.update(TABLE_NAME, createCv(entity), whereClause, whereArgs);
// }
//
// /**
// * 删除下载实体
// */
// public void delEntity(@NonNull SQLiteDatabase db, ConfigEntity entity) {
// delEntity(db, entity.getDownloadUrl());
// }
//
// /**
// * 通过下载链接删除下载实体
// */
// public void delEntity(@NonNull SQLiteDatabase db, String downloadUrl) {
// String whereClause = "url=?";
// String[] whereArgs = {downloadUrl};
// db.delete(TABLE_NAME, whereClause, whereArgs);
// }
//
// /**
// * 通过下载链接查找下载实体
// *
// * @param downloadUrl
// * @return
// */
// public ConfigEntity findEntity(@NonNull SQLiteDatabase db, @NonNull String downloadUrl) {
// ConfigEntity entity;
// String sql = "select * from " + TABLE_NAME + "where url=?";
// Cursor c = db.rawQuery(sql, new String[]{downloadUrl});
// if (c.getCount() <= 0) {
// c.close();
// return null;
// } else {
// c.moveToFirst();
// entity = cursor2Entity(c);
// }
// c.close();
// return entity;
// }
//
// /**
// * 存储下载实体
// *
// * @param entity
// */
// public void savaEntity(@NonNull SQLiteDatabase db, @NonNull ConfigEntity entity) {
// ConfigEntity temp = findEntity(db, entity.getDownloadUrl());
// if (temp == null) {
// db.insert(TABLE_NAME, null, createCv(entity));
// } else {
// updateEntity(db, entity);
// }
// }
//
// /**
// * 游标转实体
// *
// * @param c
// * @return
// */
// private ConfigEntity cursor2Entity(Cursor c) {
// ConfigEntity entity;
// entity = new ConfigEntity();
// entity.setDownloadUrl(c.getString(c.getColumnIndex("url")));
// entity.setDownloadPath(c.getString(c.getColumnIndex("path")));
// entity.setCompleteTime(c.getLong(c.getColumnIndex("completeTime")));
// entity.setFileSize(c.getLong(c.getColumnIndex("fileSize")));
// entity.setState(c.getInt(c.getColumnIndex("state")));
// // 0 ==> false, 1 ==> true
// entity.setDownloadComplete(c.getInt(c.getColumnIndex("isDownloadComplete")) == 0);
// entity.setCurrentProgress(c.getLong(c.getColumnIndex("currentProgress")));
// return entity;
// }
//
// /**
// * 创建ContentValues
// *
// * @param entity
// * @return
// */
// private ContentValues createCv(@NonNull ConfigEntity entity) {
// ContentValues cv = new ContentValues();
// cv.put("url", entity.getDownloadUrl());
// cv.put("path", entity.getDownloadPath());
// cv.put("completeTime", entity.getCompleteTime());
// cv.put("fileSize", entity.getFileSize());
// cv.put("state", entity.getState());
// // 0 ==> false, 1 ==> true
// cv.put("isDownloadComplete", entity.isDownloadComplete() ? 1 : 0);
// cv.put("currentProgress", entity.getCurrentProgress());
// return cv;
// }
//}

@ -135,30 +135,31 @@ public class Util {
public static String formatFileSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte(s)";
return size + "b";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "k";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "m";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "g";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "t";
}
/**
* 创建目录 当目录不存在的时候创建文件否则返回false
*/

Loading…
Cancel
Save