From 3a744201b57ed342488e7c43b07666657050dfa8 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Mon, 9 Jan 2017 11:15:56 +0800 Subject: [PATCH 01/24] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E9=87=8D=E8=AF=95=E9=97=B4=E9=9A=94=E4=B8=8D=E8=B5=B7=E4=BD=9C?= =?UTF-8?q?=E7=94=A8=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../aria/core/queue/DownloadTaskQueue.java | 38 +++---------------- .../arialyy/aria/core/queue/ITaskQueue.java | 7 ---- .../core/scheduler/DownloadSchedulers.java | 18 +++++---- .../arialyy/aria/core/task/DownloadUtil.java | 6 ++- .../java/com/arialyy/aria/orm/DbUtil.java | 2 - 5 files changed, 22 insertions(+), 49 deletions(-) diff --git a/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java b/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java index 06228179..d4a8f86a 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java +++ b/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java @@ -89,21 +89,15 @@ public class DownloadTaskQueue implements ITaskQueue { @Override public void stopTask(Task task) { if (!task.isDownloading()) Log.w(TAG, "停止任务失败,【任务已经停止】"); - task.stop(); - //if (task.isDownloading()) { - // if (mExecutePool.removeTask(task)) { - // task.stop(); - // } - //} else { - // task.stop(); - // Log.w(TAG, "停止任务失败,【任务已经停止】"); - //} + if (mExecutePool.removeTask(task)) { + task.stop(); + } else { + task.stop(); + Log.w(TAG, "停止任务失败,【任务已经停止】"); + } } @Override public void cancelTask(Task task) { - //if (mExecutePool.removeTask(task) || mCachePool.removeTask(task)) { - // task.cancel(); - //} task.cancel(); } @@ -119,10 +113,6 @@ public class DownloadTaskQueue implements ITaskQueue { } } - //@Override public IDownloadSchedulers getDownloadSchedulers() { - // return mSchedulers; - //} - @Override public int size() { return mExecutePool.size(); } @@ -159,12 +149,10 @@ public class DownloadTaskQueue implements ITaskQueue { @Override public Task createTask(String target, DownloadEntity entity) { Task task; if (TextUtils.isEmpty(target)) { - //task = TaskFactory.getInstance().createTask(mContext, entity, mSchedulers); task = TaskFactory.getInstance().createTask(mContext, entity, DownloadSchedulers.getInstance()); } else { task = TaskFactory.getInstance() - //.createTask(target.getClass().getName(), mContext, entity, mSchedulers); .createTask(target, mContext, entity, DownloadSchedulers.getInstance()); } mCachePool.putTask(task); @@ -197,29 +185,15 @@ public class DownloadTaskQueue implements ITaskQueue { return mCachePool.pollTask(); } - //@Override public void setScheduler(IDownloadSchedulers schedulers) { - // mSchedulers = schedulers; - //} - public static class Builder { Context context; - IDownloadSchedulers schedulers; public Builder(Context context) { this.context = context.getApplicationContext(); } - //public Builder setDownloadSchedulers(IDownloadSchedulers schedulers) { - // this.schedulers = schedulers; - // return this; - //} - public DownloadTaskQueue build() { DownloadTaskQueue queue = new DownloadTaskQueue(context); - //if (schedulers == null) { - // schedulers = DownloadSchedulers.getInstance(); - //} - //queue.setScheduler(schedulers); return queue; } } diff --git a/Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java b/Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java index 73163766..68576119 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java +++ b/Aria/src/main/java/com/arialyy/aria/core/queue/ITaskQueue.java @@ -73,11 +73,4 @@ public interface ITaskQueue extends IDownloader { * @return 下载任务 or null */ public Task getNextTask(); - - ///** - // * 设置下载调度器 - // * - // * @param schedulers 下载调度器{@link IDownloadSchedulers} - // */ - //public void setScheduler(IDownloadSchedulers schedulers); } \ No newline at end of file diff --git a/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java b/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java index 5f5b8a4e..22a7d283 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java +++ b/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java @@ -16,6 +16,7 @@ package com.arialyy.aria.core.scheduler; +import android.os.CountDownTimer; import android.os.Message; import android.text.TextUtils; import android.util.Log; @@ -154,10 +155,8 @@ public class DownloadSchedulers implements IDownloadSchedulers { private void callback(int state, Task task, OnSchedulerListener listener) { if (listener != null) { - //Task task = mQueue.getTask(entity); if (task == null) { - //Log.e(TAG, "队列中没有下载链接【" + entity.getDownloadUrl() + "】的任务"); - Log.e(TAG, "传递的下载任务"); + Log.e(TAG, "TASK 为null,回调失败"); return; } switch (state) { @@ -195,9 +194,13 @@ public class DownloadSchedulers implements IDownloadSchedulers { * @param entity 失败实体 */ @Override public void handleFailTask(final DownloadEntity entity) { - new Thread(new Runnable() { - @Override public void run() { - final Configuration config = Configuration.getInstance(); + final Configuration config = Configuration.getInstance(); + CountDownTimer timer = new CountDownTimer(config.getReTryInterval(), 1000) { + @Override public void onTick(long millisUntilFinished) { + + } + + @Override public void onFinish() { if (entity.getFailNum() <= config.getReTryNum()) { Task task = mQueue.getTask(entity); mQueue.reTryStart(task); @@ -210,7 +213,8 @@ public class DownloadSchedulers implements IDownloadSchedulers { startNextTask(entity); } } - }).start(); + }; + timer.start(); } /** diff --git a/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java b/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java index c69ee94a..d5eb65e2 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java @@ -242,12 +242,16 @@ final class DownloadUtil implements IDownloadUtil, Runnable { handleBreakpoint(conn); } else if (code == HttpURLConnection.HTTP_OK || len < 0) { //在conn.setRequestProperty("Range", "bytes=" + 0 + "-");下,200为不支持断点状态 + if (len < 0){ + failDownload("任务【" + mDownloadEntity.getDownloadUrl() + "】下载失败,文件长度小于0"); + return; + } isSupportBreakpoint = false; mListener.supportBreakpoint(false); Log.w(TAG, "该下载链接不支持断点下载"); handleBreakpoint(conn); } else { - failDownload("下载失败,返回码:" + code); + failDownload("任务【" + mDownloadEntity.getDownloadUrl() + "】下载失败,返回码:" + code); } } catch (IOException e) { failDownload("下载失败【downloadUrl:" diff --git a/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java b/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java index 4f6fe2b1..10b64600 100644 --- a/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java @@ -113,7 +113,6 @@ public class DbUtil { params[i] = "'" + expression[i + 1] + "'"; } sql = String.format(sql, params); - Log.d(TAG, sql); print(DEL_DATA, sql); mDb.execSQL(sql); close(); @@ -185,7 +184,6 @@ public class DbUtil { params[i] = "'" + expression[i + 1] + "'"; } sql = String.format(sql, params); - Log.d(TAG, sql); print(FIND_DATA, sql); Cursor cursor = mDb.rawQuery(sql, null); return cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; From d37b67cb24a55528a0fa786a485497ea616fe3fe Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Tue, 10 Jan 2017 16:47:29 +0800 Subject: [PATCH 02/24] .. --- .idea/misc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index fbb68289..5d199810 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -37,7 +37,7 @@ - + From a99a4f05bbb11ed0c588273852f4b1bd8dea9a6d Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Wed, 11 Jan 2017 17:07:16 +0800 Subject: [PATCH 03/24] =?UTF-8?q?=E6=B7=BB=E5=8A=A0https=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/misc.xml | 2 +- .../com/arialyy/aria/core/AriaManager.java | 55 ++++++--- .../arialyy/aria/core/task/DownloadUtil.java | 107 +++++++++++------ .../arialyy/aria/util/CAConfiguration.java | 9 ++ .../com/arialyy/aria/util/SSLContextUtil.java | 112 ++++++++++++++++++ .../single_task/SingleTaskActivity.java | 7 +- 6 files changed, 232 insertions(+), 60 deletions(-) create mode 100644 Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java create mode 100644 Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java diff --git a/.idea/misc.xml b/.idea/misc.xml index 5d199810..fbb68289 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -37,7 +37,7 @@ - + diff --git a/Aria/src/main/java/com/arialyy/aria/core/AriaManager.java b/Aria/src/main/java/com/arialyy/aria/core/AriaManager.java index b02cdceb..b9dcb150 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/AriaManager.java +++ b/Aria/src/main/java/com/arialyy/aria/core/AriaManager.java @@ -30,6 +30,7 @@ import android.text.TextUtils; import android.util.Log; import android.widget.PopupWindow; import com.arialyy.aria.core.command.CmdFactory; +import com.arialyy.aria.util.CAConfiguration; import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.core.command.IDownloadCmd; @@ -48,12 +49,12 @@ import java.util.Set; * Aria管理器,任务操作在这里执行 */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class AriaManager { - private static final String TAG = "AriaManager"; - private static final Object LOCK = new Object(); - private static volatile AriaManager INSTANCE = null; - private Map mTargets = new HashMap<>(); + private static final String TAG = "AriaManager"; + private static final Object LOCK = new Object(); + private static volatile AriaManager INSTANCE = null; + private Map mTargets = new HashMap<>(); private DownloadManager mManager; - private LifeCallback mLifeCallback; + private LifeCallback mLifeCallback; private AriaManager(Context context) { regAppLifeCallback(context); @@ -73,6 +74,24 @@ import java.util.Set; return getTarget(obj); } + /** + * 设置CA证书信息 + * + * @param caAlias ca证书别名 + * @param caPath assets 文件夹下的ca证书完整路径 + */ + public void setCAInfo(String caAlias, String caPath) { + if (TextUtils.isEmpty(caAlias)) { + Log.e(TAG, "ca证书别名不能为null"); + return; + } else if (TextUtils.isEmpty(caPath)) { + Log.e(TAG, "ca证书路径不能为null"); + return; + } + CAConfiguration.CA_ALIAS = caAlias; + CAConfiguration.CA_PATH = caPath; + } + /** * 获取下载列表 */ @@ -100,7 +119,7 @@ import java.util.Set; */ public void stopAllTask() { List allEntity = mManager.getAllDownloadEntity(); - List stopCmds = new ArrayList<>(); + List stopCmds = new ArrayList<>(); for (DownloadEntity entity : allEntity) { if (entity.getState() == DownloadEntity.STATE_DOWNLOAD_ING) { stopCmds.add(CommonUtil.createCmd(entity, CmdFactory.TASK_STOP)); @@ -159,8 +178,8 @@ import java.util.Set; * 删除所有任务 */ public void cancelAllTask() { - List allEntity = mManager.getAllDownloadEntity(); - List cancelCmds = new ArrayList<>(); + List allEntity = mManager.getAllDownloadEntity(); + List cancelCmds = new ArrayList<>(); for (DownloadEntity entity : allEntity) { cancelCmds.add(CommonUtil.createCmd(entity, CmdFactory.TASK_CANCEL)); } @@ -174,9 +193,9 @@ import java.util.Set; } private AMReceiver putTarget(Object obj) { - String clsName = obj.getClass().getName(); - AMReceiver target = null; - String key = ""; + String clsName = obj.getClass().getName(); + AMReceiver target = null; + String key = ""; if (!(obj instanceof Activity)) { if (obj instanceof android.support.v4.app.Fragment) { key = clsName + "_" + ((Fragment) obj).getActivity().getClass().getName(); @@ -249,12 +268,12 @@ import java.util.Set; */ private void handleDialogLift(Dialog dialog) { try { - Field dismissField = CommonUtil.getField(dialog.getClass(), "mDismissMessage"); - Message dismissMsg = (Message) dismissField.get(dialog); + Field dismissField = CommonUtil.getField(dialog.getClass(), "mDismissMessage"); + Message dismissMsg = (Message) dismissField.get(dialog); //如果Dialog已经设置Dismiss事件,则查找cancel事件 if (dismissMsg != null) { - Field cancelField = CommonUtil.getField(dialog.getClass(), "mCancelMessage"); - Message cancelMsg = (Message) cancelField.get(dialog); + Field cancelField = CommonUtil.getField(dialog.getClass(), "mCancelMessage"); + Message cancelMsg = (Message) cancelField.get(dialog); if (cancelMsg != null) { Log.e(TAG, "你已经对Dialog设置了Dismiss和cancel事件。为了防止内存泄露," + "请在dismiss方法中调用Aria.whit(this).removeSchedulerListener();来注销事件"); @@ -316,12 +335,12 @@ import java.util.Set; * onDestroy */ private void destroySchedulerListener(Object obj) { - Set keys = mTargets.keySet(); - String clsName = obj.getClass().getName(); + Set keys = mTargets.keySet(); + String clsName = obj.getClass().getName(); for (Iterator> iter = mTargets.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = iter.next(); - String key = entry.getKey(); + String key = entry.getKey(); if (key.equals(clsName) || key.contains(clsName)) { AMReceiver receiver = mTargets.get(key); if (receiver.obj != null) { diff --git a/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java b/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java index d5eb65e2..80714b08 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/core/task/DownloadUtil.java @@ -20,7 +20,9 @@ import android.content.Context; import android.util.Log; import android.util.SparseArray; import com.arialyy.aria.core.DownloadEntity; +import com.arialyy.aria.util.CAConfiguration; import com.arialyy.aria.util.CommonUtil; +import com.arialyy.aria.util.SSLContextUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -29,43 +31,47 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; +import java.net.URLConnection; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; /** * Created by lyy on 2015/8/25. * 下载工具类 */ final class DownloadUtil implements IDownloadUtil, Runnable { - private static final String TAG = "DownloadUtil"; + private static final String TAG = "DownloadUtil"; private static final Object LOCK = new Object(); /** * 线程数 */ - private final int THREAD_NUM; + private final int THREAD_NUM; //下载监听 - private IDownloadListener mListener; - private int mConnectTimeOut = 5000 * 4; //连接超时时间 - private int mReadTimeOut = 5000 * 20; //流读取的超时时间 + private IDownloadListener mListener; + private int mConnectTimeOut = 5000 * 4; //连接超时时间 + private int mReadTimeOut = 5000 * 20; //流读取的超时时间 /** * 已经完成下载任务的线程数量 */ - private boolean isDownloading = false; - private boolean isStop = false; - private boolean isCancel = false; - private boolean isNewTask = true; + private boolean isDownloading = false; + private boolean isStop = false; + private boolean isCancel = false; + private boolean isNewTask = true; private boolean isSupportBreakpoint = true; - private int mCompleteThreadNum = 0; - private int mCancelNum = 0; - private long mCurrentLocation = 0; - private int mStopNum = 0; - private int mFailNum = 0; - private Context mContext; - private DownloadEntity mDownloadEntity; + private int mCompleteThreadNum = 0; + private int mCancelNum = 0; + private long mCurrentLocation = 0; + private int mStopNum = 0; + private int mFailNum = 0; + private Context mContext; + private DownloadEntity mDownloadEntity; private ExecutorService mFixedThreadPool; - private File mDownloadFile; //下载的文件 - private File mConfigFile;//下载信息配置文件 + private File mDownloadFile; //下载的文件 + private File mConfigFile;//下载信息配置文件 private SparseArray mTask = new SparseArray<>(); DownloadUtil(Context context, DownloadEntity entity, IDownloadListener downloadListener) { @@ -222,8 +228,8 @@ final class DownloadUtil implements IDownloadUtil, Runnable { @Override public void run() { try { - URL url = new URL(mDownloadEntity.getDownloadUrl()); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + URL url = new URL(mDownloadEntity.getDownloadUrl()); + HttpURLConnection conn = handleConnection(url); setConnectParam(conn); conn.setRequestProperty("Range", "bytes=" + 0 + "-"); conn.setConnectTimeout(mConnectTimeOut * 4); @@ -242,7 +248,7 @@ final class DownloadUtil implements IDownloadUtil, Runnable { handleBreakpoint(conn); } else if (code == HttpURLConnection.HTTP_OK || len < 0) { //在conn.setRequestProperty("Range", "bytes=" + 0 + "-");下,200为不支持断点状态 - if (len < 0){ + if (len < 0) { failDownload("任务【" + mDownloadEntity.getDownloadUrl() + "】下载失败,文件长度小于0"); return; } @@ -263,6 +269,30 @@ final class DownloadUtil implements IDownloadUtil, Runnable { } } + /** + * 处理链接 + * + * @throws IOException + */ + private HttpURLConnection handleConnection(URL url) throws IOException { + HttpURLConnection conn; + URLConnection urlConn = url.openConnection(); + if (urlConn instanceof HttpsURLConnection) { + conn = (HttpsURLConnection) urlConn; + SSLContext sslContext = + SSLContextUtil.getSSLContext(CAConfiguration.CA_ALIAS, CAConfiguration.CA_ALIAS); + if (sslContext == null) { + sslContext = SSLContextUtil.getDefaultSLLContext(); + } + SSLSocketFactory ssf = sslContext.getSocketFactory(); + ((HttpsURLConnection) conn).setSSLSocketFactory(ssf); + ((HttpsURLConnection) conn).setHostnameVerifier(SSLContextUtil.HOSTNAME_VERIFIER); + } else { + conn = (HttpURLConnection) urlConn; + } + return conn; + } + /** * 处理断点 */ @@ -305,15 +335,15 @@ final class DownloadUtil implements IDownloadUtil, Runnable { } } } - int blockSize = fileLength / THREAD_NUM; - int[] recordL = new int[THREAD_NUM]; - int rl = 0; + int blockSize = fileLength / THREAD_NUM; + int[] recordL = new int[THREAD_NUM]; + int rl = 0; for (int i = 0; i < THREAD_NUM; i++) { recordL[i] = -1; } for (int i = 0; i < THREAD_NUM; i++) { - long startL = i * blockSize, endL = (i + 1) * blockSize; - Object state = pro.getProperty(mDownloadFile.getName() + "_state_" + i); + long startL = i * blockSize, endL = (i + 1) * blockSize; + Object state = pro.getProperty(mDownloadFile.getName() + "_state_" + i); if (state != null && Integer.parseInt(state + "") == 1) { //该线程已经完成 mCurrentLocation += endL - startL; Log.d(TAG, "++++++++++ 线程_" + i + "_已经下载完成 ++++++++++"); @@ -381,12 +411,12 @@ final class DownloadUtil implements IDownloadUtil, Runnable { */ private static class ConfigEntity { //文件大小 - long fileSize; - String downloadUrl; - int threadId; - long startLocation; - long endLocation; - File tempFile; + long fileSize; + String downloadUrl; + int threadId; + long startLocation; + long endLocation; + File tempFile; } /** @@ -395,7 +425,7 @@ final class DownloadUtil implements IDownloadUtil, Runnable { private class SingleThreadTask implements Runnable { private static final String TAG = "SingleThreadTask"; private ConfigEntity configEntity; - private String configFPath; + private String configFPath; private long currentLocation = 0; private SingleThreadTask(ConfigEntity downloadInfo) { @@ -410,10 +440,11 @@ final class DownloadUtil implements IDownloadUtil, Runnable { @Override public void run() { HttpURLConnection conn = null; - InputStream is = null; + InputStream is = null; try { URL url = new URL(configEntity.downloadUrl); - conn = (HttpURLConnection) url.openConnection(); + //conn = (HttpURLConnection) url.openConnection(); + conn = handleConnection(url); if (isSupportBreakpoint) { Log.d(TAG, "线程_" + configEntity.threadId @@ -437,7 +468,7 @@ final class DownloadUtil implements IDownloadUtil, Runnable { //设置每条线程写入文件的位置 file.seek(configEntity.startLocation); byte[] buffer = new byte[1024]; - int len; + int len; //当前子线程的下载位置 currentLocation = configEntity.startLocation; while ((len = is.read(buffer)) != -1) { @@ -597,8 +628,8 @@ final class DownloadUtil implements IDownloadUtil, Runnable { * 将记录写入到配置文件 */ private void writeConfig(String key, String record) throws IOException { - File configFile = new File(configFPath); - Properties pro = CommonUtil.loadConfig(configFile); + File configFile = new File(configFPath); + Properties pro = CommonUtil.loadConfig(configFile); pro.setProperty(key, record); CommonUtil.saveConfig(configFile, pro); } diff --git a/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java b/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java new file mode 100644 index 00000000..903653ce --- /dev/null +++ b/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java @@ -0,0 +1,9 @@ +package com.arialyy.aria.util; + +/** + * Created by Aria.Lao on 2017/1/11. + */ + +public class CAConfiguration { + public static String CA_PATH, CA_ALIAS; +} diff --git a/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java new file mode 100644 index 00000000..6ab8f3dc --- /dev/null +++ b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java @@ -0,0 +1,112 @@ +package com.arialyy.aria.util; + +import com.arialyy.aria.core.DownloadManager; +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +/** + * Created by Aria.Lao on 2017/1/11. + */ + +public class SSLContextUtil { + + /** + * 颁发服务器证书的 CA 未知 + * + * @param caAlias CA证书别名 + * @param caPath 保存在assets目录下的CA证书完整路径 + */ + public static SSLContext getSSLContext(String caAlias, String caPath) { + // Load CAs from an InputStream + // (could be from a resource or ByteArrayInputStream or ...) + CertificateFactory cf = null; + try { + cf = CertificateFactory.getInstance("X.509"); + InputStream caInput = DownloadManager.APP.getAssets().open(caPath); + Certificate ca; + ca = cf.generateCertificate(caInput); + System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); + + // Create a KeyStore containing our trusted CAs + String keyStoreType = KeyStore.getDefaultType(); + KeyStore keyStore = KeyStore.getInstance(keyStoreType); + keyStore.load(null, null); + keyStore.setCertificateEntry(caAlias, ca); + + // Create a TrustManager that trusts the CAs in our KeyStore + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + tmf.init(keyStore); + KeyManagerFactory kmf = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, null); + + // Create an SSLContext that uses our TrustManager + SSLContext context = SSLContext.getInstance("TLS"); + context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); + return context; + } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | KeyManagementException | UnrecoverableKeyException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 服务器证书不是由 CA 签署的,而是自签署时,获取默认的SSL + */ + public static SSLContext getDefaultSLLContext() { + SSLContext sslContext = null; + try { + sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, new TrustManager[] { trustManagers }, new SecureRandom()); + } catch (Exception e) { + e.printStackTrace(); + } + return sslContext; + } + + /** + * 创建自己的 TrustManager,这次直接信任服务器证书。这种方法具有前面所述的将应用与证书直接关联的所有弊端,但可以安全地操作。 + */ + private static TrustManager trustManagers = new X509TrustManager() { + + @Override public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + } + + @Override public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + + } + + @Override public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + + public static final HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; +} diff --git a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java index b66ae0b4..9972c4ab 100644 --- a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java +++ b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java @@ -49,10 +49,10 @@ public class SingleTaskActivity extends BaseActivity { public static final int DOWNLOAD_RESUME = 0x05; public static final int DOWNLOAD_COMPLETE = 0x06; public static final int DOWNLOAD_RUNNING = 0x07; + private static final String DOWNLOAD_URL = - "http://static.gaoshouyou.com/d/3a/93/573ae1db9493a801c24bf66128b11e39.apk"; - //private static final String DOWNLOAD_URL = - // "http://www.yangqiang.im/wp-content/uploads/2016/10/%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F.png"; + //"http://kotlinlang.org/docs/kotlin-docs.pdf"; + "https://dl.google.com/dl/android/studio/install/2.2.3.0/android-studio-bundle-145.3537739-windows.exe"; @Bind(R.id.progressBar) HorizontalProgressBarWithNumber mPb; @Bind(R.id.start) Button mStart; @Bind(R.id.stop) Button mStop; @@ -114,6 +114,7 @@ public class SingleTaskActivity extends BaseActivity { setBtState(false); break; case DOWNLOAD_COMPLETE: + mPb.setProgress(100); Toast.makeText(SingleTaskActivity.this, "下载完成", Toast.LENGTH_SHORT).show(); mStart.setText("重新开始?"); mCancel.setEnabled(false); From deb70fa7e1cd63e9fddab27320d82a27bad357c2 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Wed, 11 Jan 2017 17:40:23 +0800 Subject: [PATCH 04/24] =?UTF-8?q?=E6=B7=BB=E5=8A=A0https=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/arialyy/aria/util/CAConfiguration.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java b/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java index 903653ce..ac755396 100644 --- a/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java +++ b/Aria/src/main/java/com/arialyy/aria/util/CAConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.arialyy.aria.util; /** From 44e3ef62f5af598e547e8e4d6962d5f82dafeb30 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Thu, 12 Jan 2017 11:06:05 +0800 Subject: [PATCH 05/24] =?UTF-8?q?readme=20=E7=BC=96=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 21 +++++++++++++++---- .../single_task/SingleTaskActivity.java | 2 +- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 97ca626b..8ad1b810 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Aria,致力于让下载傻瓜化
- 支持多线程、多任务下载 - 支持任务自动切换 - 支持下载速度直接获取 + - 支持https地址下载 [Aria怎样使用?](#使用) @@ -16,11 +17,9 @@ Aria,致力于让下载傻瓜化
## 下载 [![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)
```java -compile 'com.arialyy.aria:Aria:2.3.8' +compile 'com.arialyy.aria:Aria:2.3.9' ``` - - ## 示例 ![多任务下载](https://github.com/AriaLyy/DownloadUtil/blob/v_2.0/img/download_img.gif) ![Dialog使用](https://github.com/AriaLyy/DownloadUtil/blob/v_2.0/img/dialog_use.gif "") @@ -52,6 +51,7 @@ compile 'com.arialyy.aria:Aria:2.3.8' } ``` ### 四、通过下载链接,你还能使用Aria执行很多操作,如: +Aria支持https下载,如果你希望使用自己的ca证书,那么你需要进行[Aria https证书配置](#https证书配置) - 添加任务(不进行下载) ```java @@ -118,8 +118,22 @@ compile 'com.arialyy.aria:Aria:2.3.8' Aria.get(this).openBroadcast(true); ``` +### https证书配置 + + 将你的证书导入`assets`目录 + + 调用以下代码配置ca证书相关信息 + ```java + /** + * 设置CA证书信息 + * + * @param caAlias ca证书别名 + * @param caPath assets 文件夹下的ca证书完整路径 + */ + Aria.get(this).setCAInfo("caAlias","caPath"); + ``` + *** ## 开发日志 + + v_2.3.9 支持https链接下载 + v_2.3.8 修复数据错乱的bug、添加fragment支持 + v_2.3.6 添加dialog、popupWindow支持 + v_2.3.3 @@ -128,7 +142,6 @@ compile 'com.arialyy.aria:Aria:2.3.8' - 修复一个内存泄露的bug + v_2.3.1 重命名为Aria,下载流程简化 + v_2.1.1 增加,选择最大下载任务数接口 - + v_2.1.0 修复大量bug License ------- diff --git a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java index 9972c4ab..04639b8b 100644 --- a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java +++ b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java @@ -52,7 +52,7 @@ public class SingleTaskActivity extends BaseActivity { private static final String DOWNLOAD_URL = //"http://kotlinlang.org/docs/kotlin-docs.pdf"; - "https://dl.google.com/dl/android/studio/install/2.2.3.0/android-studio-bundle-145.3537739-windows.exe"; + "https://atom-installer.github.com/v1.13.0/AtomSetup.exe?s=1484074138&ext=.exe"; @Bind(R.id.progressBar) HorizontalProgressBarWithNumber mPb; @Bind(R.id.start) Button mStart; @Bind(R.id.stop) Button mStop; From 53559ac1dbda32a9a4420eeed134cb7fb091cd42 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Thu, 12 Jan 2017 11:12:26 +0800 Subject: [PATCH 06/24] readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8ad1b810..2e061261 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ Aria支持https下载,如果你希望使用自己的ca证书,那么你需要 ### https证书配置 + 将你的证书导入`assets`目录 + 调用以下代码配置ca证书相关信息 + ```java /** * 设置CA证书信息 From 8de93e93d6180871d61a4f7dc9d7c9faf487046d Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Thu, 12 Jan 2017 11:21:08 +0800 Subject: [PATCH 07/24] bug fix --- Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java | 4 ++++ README.md | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java index 6ab8f3dc..b17da02e 100644 --- a/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java @@ -1,5 +1,6 @@ package com.arialyy.aria.util; +import android.text.TextUtils; import com.arialyy.aria.core.DownloadManager; import java.io.BufferedInputStream; import java.io.FileInputStream; @@ -37,6 +38,9 @@ public class SSLContextUtil { * @param caPath 保存在assets目录下的CA证书完整路径 */ public static SSLContext getSSLContext(String caAlias, String caPath) { + if (TextUtils.isEmpty(caAlias) || TextUtils.isEmpty(caPath)){ + return null; + } // Load CAs from an InputStream // (could be from a resource or ByteArrayInputStream or ...) CertificateFactory cf = null; diff --git a/README.md b/README.md index 2e061261..ddc19c92 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Aria,致力于让下载傻瓜化
## 下载 [![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)
```java -compile 'com.arialyy.aria:Aria:2.3.9' +compile 'com.arialyy.aria:Aria:2.4.0' ``` ## 示例 @@ -134,7 +134,7 @@ Aria支持https下载,如果你希望使用自己的ca证书,那么你需要 *** ## 开发日志 - + v_2.3.9 支持https链接下载 + + v_2.4.0 支持https链接下载 + v_2.3.8 修复数据错乱的bug、添加fragment支持 + v_2.3.6 添加dialog、popupWindow支持 + v_2.3.3 From 212d635f8572d7eb20d6df8138420e5e163a04a2 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Thu, 12 Jan 2017 11:28:13 +0800 Subject: [PATCH 08/24] .. --- .../java/com/arialyy/simple/single_task/SingleTaskActivity.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java index 04639b8b..10da33dd 100644 --- a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java +++ b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java @@ -89,7 +89,7 @@ public class SingleTaskActivity extends BaseActivity { case DOWNLOAD_PRE: mSize.setText(CommonUtil.formatFileSize((Long) msg.obj)); setBtState(false); - mStart.setText("暂停"); + //mStart.setText("暂停"); break; case DOWNLOAD_FAILE: Toast.makeText(SingleTaskActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); From 7cea89786561b48607436e2fa3bde1e09e2a2959 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Mon, 16 Jan 2017 19:18:31 +0800 Subject: [PATCH 09/24] .. --- .idea/misc.xml | 2 +- .../arialyy/aria/core/queue/DownloadTaskQueue.java | 11 ++++------- .../aria/core/scheduler/DownloadSchedulers.java | 6 +++--- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index fbb68289..5d199810 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -37,7 +37,7 @@
- + diff --git a/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java b/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java index d4a8f86a..de033a65 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java +++ b/Aria/src/main/java/com/arialyy/aria/core/queue/DownloadTaskQueue.java @@ -33,9 +33,9 @@ import com.arialyy.aria.util.Configuration; * 下载任务队列 */ public class DownloadTaskQueue implements ITaskQueue { - private static final String TAG = "DownloadTaskQueue"; - private CachePool mCachePool = CachePool.getInstance(); - private ExecutePool mExecutePool = ExecutePool.getInstance(); + private static final String TAG = "DownloadTaskQueue"; + private CachePool mCachePool = CachePool.getInstance(); + private ExecutePool mExecutePool = ExecutePool.getInstance(); private Context mContext; //private IDownloadSchedulers mSchedulers; @@ -171,13 +171,10 @@ public class DownloadTaskQueue implements ITaskQueue { Task task = mExecutePool.getTask(entity.getDownloadUrl()); if (task != null) { Log.d(TAG, "从执行池删除任务,删除" + (mExecutePool.removeTask(task) ? "成功" : "失败")); - } else { - task = mCachePool.getTask(entity.getDownloadUrl()); } + task = mCachePool.getTask(entity.getDownloadUrl()); if (task != null) { Log.d(TAG, "从缓存池删除任务,删除" + (mCachePool.removeTask(task) ? "成功" : "失败")); - } else { - Log.w(TAG, "没有找到下载链接为【" + entity.getDownloadUrl() + "】的任务"); } } diff --git a/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java b/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java index 22a7d283..25e9385c 100644 --- a/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java +++ b/Aria/src/main/java/com/arialyy/aria/core/scheduler/DownloadSchedulers.java @@ -121,15 +121,16 @@ public class DownloadSchedulers implements IDownloadSchedulers { case STOP: case CANCEL: mQueue.removeTask(entity); - mQueue.removeTask(entity); - if (mQueue.size() != Configuration.getInstance().getDownloadNum()) { + if (mQueue.size() < Configuration.getInstance().getDownloadNum()) { startNextTask(entity); } break; case COMPLETE: + mQueue.removeTask(entity); startNextTask(entity); break; case FAIL: + mQueue.removeTask(entity); handleFailTask(entity); break; } @@ -223,7 +224,6 @@ public class DownloadSchedulers implements IDownloadSchedulers { * @param entity 通过Handler传递的下载实体 */ @Override public void startNextTask(DownloadEntity entity) { - mQueue.removeTask(entity); Task newTask = mQueue.getNextTask(); if (newTask == null) { Log.w(TAG, "没有下一任务"); From 01ae7e2e5fd92dae7f48944f2789449a609d27b9 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Wed, 18 Jan 2017 09:43:41 +0800 Subject: [PATCH 10/24] .. --- .idea/misc.xml | 2 +- .../com/arialyy/aria/util/SSLContextUtil.java | 17 ++++++++++++++++- .../simple/single_task/SingleTaskActivity.java | 7 ------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index fbb68289..5d199810 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -37,7 +37,7 @@ - + diff --git a/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java index b17da02e..af40e0de 100644 --- a/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/util/SSLContextUtil.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.arialyy.aria.util; import android.text.TextUtils; @@ -38,7 +53,7 @@ public class SSLContextUtil { * @param caPath 保存在assets目录下的CA证书完整路径 */ public static SSLContext getSSLContext(String caAlias, String caPath) { - if (TextUtils.isEmpty(caAlias) || TextUtils.isEmpty(caPath)){ + if (TextUtils.isEmpty(caAlias) || TextUtils.isEmpty(caPath)) { return null; } // Load CAs from an InputStream diff --git a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java index 10da33dd..82d62924 100644 --- a/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java +++ b/app/src/main/java/com/arialyy/simple/single_task/SingleTaskActivity.java @@ -119,11 +119,6 @@ public class SingleTaskActivity extends BaseActivity { mStart.setText("重新开始?"); mCancel.setEnabled(false); setBtState(true); - - //String path = Environment.getExternalStorageDirectory().getPath() + "/test.jpg"; - //Bitmap bm = BitmapFactory.decodeFile(path); - //mImg.setImageBitmap(bm); - break; } } @@ -201,8 +196,6 @@ public class SingleTaskActivity extends BaseActivity { .load(DOWNLOAD_URL) .setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/test.apk") .setDownloadName("test.apk") - //.setDownloadPath(Environment.getExternalStorageDirectory().getPath() + "/test.jpg") - //.setDownloadName("test.jpg") .start(); } From 9bba3cd899d400aadfee511a0216183b34257944 Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Wed, 18 Jan 2017 11:27:09 +0800 Subject: [PATCH 11/24] =?UTF-8?q?=E6=B7=BB=E5=8A=A0notification=E4=BE=8B?= =?UTF-8?q?=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/arialyy/simple/MainActivity.java | 5 + .../notification/SimpleNotification.java | 98 +++++++++++++++++++ app/src/main/res/layout/activity_main.xml | 9 ++ 3 files changed, 112 insertions(+) create mode 100644 app/src/main/java/com/arialyy/simple/notification/SimpleNotification.java diff --git a/app/src/main/java/com/arialyy/simple/MainActivity.java b/app/src/main/java/com/arialyy/simple/MainActivity.java index 33a10ee8..0df80bbc 100644 --- a/app/src/main/java/com/arialyy/simple/MainActivity.java +++ b/app/src/main/java/com/arialyy/simple/MainActivity.java @@ -33,6 +33,7 @@ import com.arialyy.simple.databinding.ActivityMainBinding; import com.arialyy.simple.dialog_task.DownloadDialog; import com.arialyy.simple.fragment_task.FragmentActivity; import com.arialyy.simple.multi_task.MultiTaskActivity; +import com.arialyy.simple.notification.SimpleNotification; import com.arialyy.simple.pop_task.DownloadPopupWindow; import com.arialyy.simple.single_task.SingleTaskActivity; @@ -104,6 +105,10 @@ public class MainActivity extends BaseActivity { case R.id.fragment_task: startActivity(new Intent(this, FragmentActivity.class)); break; + case R.id.notification: + SimpleNotification notification = new SimpleNotification(this); + notification.start(); + break; } } } \ No newline at end of file diff --git a/app/src/main/java/com/arialyy/simple/notification/SimpleNotification.java b/app/src/main/java/com/arialyy/simple/notification/SimpleNotification.java new file mode 100644 index 00000000..3d11fd69 --- /dev/null +++ b/app/src/main/java/com/arialyy/simple/notification/SimpleNotification.java @@ -0,0 +1,98 @@ +package com.arialyy.simple.notification; + +import android.app.NotificationManager; +import android.content.Context; +import android.os.Environment; +import android.support.v4.app.NotificationCompat; +import com.arialyy.aria.core.Aria; +import com.arialyy.aria.core.task.Task; +import com.arialyy.frame.util.show.L; +import com.arialyy.frame.util.show.T; +import com.arialyy.simple.R; + +/** + * Created by Aria.Lao on 2017/1/18. + */ + +public class SimpleNotification { + private static final String DOWNLOAD_URL = + "http://static.gaoshouyou.com/d/6e/e5/ff6ecaaf45e532e6d07747af82357472.apk"; + + private NotificationManager mManager; + private Context mContext; + private NotificationCompat.Builder mBuilder; + private static final int mNotifiyId = 0; + + public SimpleNotification(Context context) { + mContext = context; + init(); + } + + private void init() { + mManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); + mBuilder = new NotificationCompat.Builder(mContext); + mBuilder.setContentTitle("Aria Download Test") + .setContentText("进度条") + .setProgress(100, 0, false) + .setSmallIcon(R.mipmap.ic_launcher); + mManager.notify(mNotifiyId, mBuilder.build()); + Aria.whit(mContext).addSchedulerListener(new DownloadCallback(mBuilder, mManager)); + } + + public void start() { + Aria.whit(mContext) + .load(DOWNLOAD_URL) + .setDownloadName("notification_test.apk") + .setDownloadPath( + Environment.getExternalStorageDirectory() + "/Download/notification_test.apk") + .start(); + } + + public void stop() { + Aria.whit(mContext).load(DOWNLOAD_URL).stop(); + } + + private static class DownloadCallback extends Aria.SimpleSchedulerListener { + NotificationCompat.Builder mBuilder; + NotificationManager mManager; + + private DownloadCallback(NotificationCompat.Builder builder, NotificationManager manager) { + mBuilder = builder; + mManager = manager; + } + + @Override public void onTaskStart(Task task) { + super.onTaskStart(task); + } + + @Override public void onTaskPre(Task task) { + super.onTaskPre(task); + } + + @Override public void onTaskStop(Task task) { + super.onTaskStop(task); + } + + @Override public void onTaskRunning(Task task) { + super.onTaskRunning(task); + long len = task.getFileSize(); + int p = (int) (task.getCurrentProgress() * 100 / len); + if (mBuilder != null) { + mBuilder.setProgress(100, p, false); + mManager.notify(mNotifiyId, mBuilder.build()); + } + } + + @Override public void onTaskComplete(Task task) { + super.onTaskComplete(task); + if (mBuilder != null) { + mBuilder.setProgress(100, 100, false); + mManager.notify(mNotifiyId, mBuilder.build()); + } + } + + @Override public void onTaskCancel(Task task) { + super.onTaskCancel(task); + } + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 464bb3a5..08ccd012 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -56,5 +56,14 @@ style="?buttonBarButtonStyle" /> +