Ver Fonte

提交2.0.4测试版本8,添加下载文件覆盖,还没测下载断点下载方式

yanyi há 4 anos atrás
pai
commit
fd8d005515

+ 38 - 2
app/src/main/java/com/mylove/okhttp/MainActivity.java

@@ -1,5 +1,6 @@
 package com.mylove.okhttp;
 
+import android.Manifest;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.View;
@@ -9,6 +10,8 @@ import androidx.appcompat.app.AppCompatActivity;
 
 import com.benyanyi.loglib.Jlog;
 import com.benyanyi.okhttp.OkHttpUtil;
+import com.benyanyi.okhttp.download.DownloadInfo;
+import com.benyanyi.okhttp.listener.OnDownLoadObserver;
 import com.benyanyi.okhttp.listener.OnOkHttpListener;
 import com.benyanyi.permissionlib.PermissionCallBack;
 import com.benyanyi.permissionlib.PermissionHelper;
@@ -32,8 +35,23 @@ public class MainActivity extends AppCompatActivity {
         super.onCreate(savedInstanceState);
 //        setContentView(R.layout.notification_contentview);
         setContentView(R.layout.activity_main);
-        init();
+//        init();
+        PermissionHelper.getInstance(this).hasPermission(0x11, new PermissionCallBack() {
+            @Override
+            public void onPermissionSuccess(int permissionCode) {
+                downloadAPK();
+            }
+
+            @Override
+            public void onPermissionFailure(FailureMsg failureMsg) {
+
+            }
+
+            @Override
+            public void onPermissionComplete(int permissionCode) {
 
+            }
+        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
 //        permissionHelper = new PermissionHelper(this, strings);
 //        permissionHelper.hasPermission(new PermissionHelper.OnPermissionListener() {
 //            @Override
@@ -111,9 +129,27 @@ public class MainActivity extends AppCompatActivity {
 
     private void downloadAPK() {
 //        JLog.init(true);
-        String url = "http://qxu1590330342.my3w.com/bluetooth/dectector/dectector.apk";
+        String url = "http://apitest.yanyi.online/app/xiangyou.apk";
 //        String filePath = "/dectector/dfu/";
 ////        String filePath = Environment.getExternalStorageDirectory().toString() + "/dectector/dfu/";
+        OkHttpUtil.getInstance(this).url(url).download(true).start(new OnDownLoadObserver() {
+            @Override
+            public void onComplete() {
+
+            }
+
+            @Override
+            public void onNext(DownloadInfo downloadInfo) {
+                super.onNext(downloadInfo);
+                Jlog.v(downloadInfo);
+            }
+
+            @Override
+            public void onError(Throwable e) {
+                super.onError(e);
+                Jlog.e(e.getMessage());
+            }
+        });
 //        OkHttpUtil.getInstance(this).downloadFile(url).downloads(filePath, new OnDownloadCallBack() {
 //            @Override
 //            public void onDownloading(int progress) {

+ 10 - 11
okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadCall.java

@@ -3,7 +3,6 @@ package com.benyanyi.okhttp.download;
 import android.content.Context;
 
 import com.benyanyi.okhttp.listener.OnDownLoadObserver;
-import com.benyanyi.okhttp.util.FormatUtil;
 
 /**
  * @author YanYi
@@ -16,29 +15,23 @@ public class DownloadCall implements DownloadConfig {
     private Context mContext;
     private String url;
     private String suffix;
+    private boolean isCover;
 
     private DownloadCall(Builder builder) {
         this.mContext = builder.mContext;
         this.url = builder.url;
         this.suffix = builder.suffix;
+        this.isCover = builder.isCover;
     }
 
     @Override
     public void start() {
-        if (FormatUtil.isEmpty(this.suffix)) {
-            DownloadManager.getInstance(mContext).download(url);
-        } else {
-            DownloadManager.getInstance(mContext).download(url, suffix);
-        }
+        DownloadManager.getInstance(mContext).download(url, isCover, suffix);
     }
 
     @Override
     public void start(OnDownLoadObserver onDownLoadObserver) {
-        if (FormatUtil.isEmpty(this.suffix)) {
-            DownloadManager.getInstance(mContext).download(url, onDownLoadObserver);
-        } else {
-            DownloadManager.getInstance(mContext).download(url, suffix, onDownLoadObserver);
-        }
+        DownloadManager.getInstance(mContext).download(url, isCover, suffix, onDownLoadObserver);
     }
 
     @Override
@@ -66,6 +59,7 @@ public class DownloadCall implements DownloadConfig {
         private Context mContext;
         private String url;
         private String suffix;
+        private boolean isCover;
 
         public Builder setContext(Context mContext) {
             this.mContext = mContext;
@@ -82,6 +76,11 @@ public class DownloadCall implements DownloadConfig {
             return this;
         }
 
+        public Builder setCover(boolean cover) {
+            isCover = cover;
+            return this;
+        }
+
         public DownloadConfig builder() {
             return new DownloadCall(this);
         }

+ 81 - 47
okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadManager.java

@@ -3,6 +3,7 @@ package com.benyanyi.okhttp.download;
 import android.content.Context;
 
 import com.benyanyi.okhttp.listener.OnDownLoadObserver;
+import com.benyanyi.okhttp.util.OkHttpLog;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -45,6 +46,7 @@ class DownloadManager {
     private Context mContext;
 
     private String suffix = "";//文件名后缀
+    private boolean isCover = false;//是否覆盖之前的文件
 
     /**
      * 获得一个单例类
@@ -95,10 +97,12 @@ class DownloadManager {
     /**
      * 开始下载
      *
-     * @param suffix 文件名后缀
-     * @param url    下载请求的网址
+     * @param url     下载请求的网址
+     * @param isCover 是否覆盖之前的文件
+     * @param suffix  文件名后缀
      */
-    void download(String url, String suffix) {
+    void download(String url, boolean isCover, String suffix) {
+        this.isCover = isCover;
         this.suffix = suffix;
         this.download(url);
     }
@@ -106,11 +110,13 @@ class DownloadManager {
     /**
      * 开始下载
      *
-     * @param suffix             文件名后缀
      * @param url                下载请求的网址
+     * @param isCover            是否覆盖之前的文件
+     * @param suffix             文件名后缀
      * @param onDownLoadObserver 用来回调的接口
      */
-    void download(String url, String suffix, OnDownLoadObserver onDownLoadObserver) {
+    void download(String url, boolean isCover, String suffix, OnDownLoadObserver onDownLoadObserver) {
+        this.isCover = isCover;
         this.suffix = suffix;
         this.download(url, onDownLoadObserver);
     }
@@ -120,7 +126,7 @@ class DownloadManager {
      *
      * @param url 下载请求的网址
      */
-    void download(String url) {
+    private void download(String url) {
         DownloadObserver observer = new DownloadObserver();
         observer.setContext(mContext);
         Observable.just(url)
@@ -159,7 +165,7 @@ class DownloadManager {
                 .subscribe(observer);
     }
 
-    void download(String url, OnDownLoadObserver onDownLoadObserver) {
+    private void download(String url, OnDownLoadObserver onDownLoadObserver) {
         Observable.just(url)
                 //call的map已经有了,就证明正在下载,则这次不下载
                 .filter(new Predicate<String>() {
@@ -261,24 +267,30 @@ class DownloadManager {
         long downloadLength = 0, contentLength = downloadInfo.getTotal();
         File file = new File(savePath, fileName);
         if (file.exists()) {
-            //找到了文件,代表已经下载过,则获取其长度
-            downloadLength = file.length();
-        }
-        //之前下载过,需要重新来一个文件
-        int i = 1;
-        while (downloadLength >= contentLength) {
-            int dotIndex = fileName.lastIndexOf(".");
-            String fileNameOther;
-            if (dotIndex == -1) {
-                fileNameOther = fileName + "(" + i + ")";
+            if (isCover) {
+                file.delete();
             } else {
-                fileNameOther = fileName.substring(0, dotIndex)
-                        + "(" + i + ")" + fileName.substring(dotIndex);
+                //找到了文件,代表已经下载过,则获取其长度
+                downloadLength = file.length();
+            }
+        }
+        if (!isCover) {
+            //之前下载过,需要重新来一个文件
+            int i = 1;
+            while (downloadLength >= contentLength) {
+                int dotIndex = fileName.lastIndexOf(".");
+                String fileNameOther;
+                if (dotIndex == -1) {
+                    fileNameOther = fileName + "(" + i + ")";
+                } else {
+                    fileNameOther = fileName.substring(0, dotIndex)
+                            + "(" + i + ")" + fileName.substring(dotIndex);
+                }
+                File newFile = new File(savePath, fileNameOther);
+                file = newFile;
+                downloadLength = newFile.length();
+                i++;
             }
-            File newFile = new File(savePath, fileNameOther);
-            file = newFile;
-            downloadLength = newFile.length();
-            i++;
         }
         //设置改变过的文件名/大小
         downloadInfo.setProgress(downloadLength);
@@ -295,7 +307,7 @@ class DownloadManager {
         }
 
         @Override
-        public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception {
+        public void subscribe(ObservableEmitter<DownloadInfo> e) {
             String url = downloadInfo.getUrl();
             //已经下载好的长度
             long downloadLength = downloadInfo.getProgress();
@@ -313,32 +325,54 @@ class DownloadManager {
             //把这个添加到call里,方便取消
             downCalls.put(url, call);
             downInfos.put(url, downloadInfo);
-            Response response = call.execute();
-            String savePath = FileUtil.isExistDir(mContext.getPackageName());
-            File file = new File(savePath, downloadInfo.getFileName());
-            InputStream is = null;
-            FileOutputStream fileOutputStream = null;
+            Response response;
             try {
-                is = response.body().byteStream();
-                fileOutputStream = new FileOutputStream(file, true);
-                //缓冲数组2kB
-                byte[] buffer = new byte[2048];
-                int len;
-                while ((len = is.read(buffer)) != -1) {
-                    fileOutputStream.write(buffer, 0, len);
-                    downloadLength += len;
-                    downloadInfo.setProgress(downloadLength);
-                    downInfos.put(url, downloadInfo);
-                    e.onNext(downloadInfo);
+                response = call.execute();
+                String savePath = FileUtil.isExistDir(mContext.getPackageName());
+                File file = new File(savePath, downloadInfo.getFileName());
+                InputStream is = null;
+                FileOutputStream fileOutputStream = null;
+                try {
+                    if (response.body() == null) {
+                        e.onError(new Throwable("下载文件为空"));
+                    } else {
+                        is = response.body().byteStream();
+                        fileOutputStream = new FileOutputStream(file, true);
+                        //缓冲数组2kB
+                        byte[] buffer = new byte[2048];
+                        int len;
+                        while ((len = is.read(buffer)) != -1) {
+                            fileOutputStream.write(buffer, 0, len);
+                            downloadLength += len;
+                            downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_ING);
+                            downloadInfo.setProgress(downloadLength);
+                            downInfos.put(url, downloadInfo);
+                            e.onNext(downloadInfo);
+                        }
+                        downloadInfo.setFile(file);
+                        fileOutputStream.flush();
+                        downCalls.remove(url);
+                        downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_OVER);
+                        //关闭IO流
+                        IoUtil.closeAll(is, fileOutputStream);
+                        e.onComplete();//完成
+                    }
+                } catch (Exception ex) {
+                    if (ex.getMessage() != null && ex.getMessage().equals("Software caused connection abort")) {
+                        OkHttpLog.e("网络断开");
+                    }
+                    pause(url);
+                    downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_ERROR);
+                    e.onError(ex);
+//                } finally {
+                    //关闭IO流
+//                    IoUtil.closeAll(is, fileOutputStream);
                 }
-                downloadInfo.setFile(file);
-                fileOutputStream.flush();
-                downCalls.remove(url);
-            } finally {
-                //关闭IO流
-                IoUtil.closeAll(is, fileOutputStream);
+            } catch (IOException ex) {
+                pause(url);
+                downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_ERROR);
+                e.onError(ex);
             }
-            e.onComplete();//完成
         }
     }
 

+ 6 - 2
okhttplib/src/main/java/com/benyanyi/okhttp/type/Client.java

@@ -16,9 +16,13 @@ import okhttp3.Protocol;
  */
 class Client {
 
-    static OkHttpClient getClient(Context context, boolean isCache) {
+    static OkHttpClient getClient(Context context, boolean isCache, boolean isFile) {
         OkHttpClient.Builder builder = new OkHttpClient.Builder();
-        builder.addNetworkInterceptor(HttpConfig.HTTP_LOGGING_INTERCEPTOR);
+        if (isFile) {
+            builder.addNetworkInterceptor(HttpConfig.HTTP_LOGGING_INTERCEPTOR_FILE);
+        } else {
+            builder.addNetworkInterceptor(HttpConfig.HTTP_LOGGING_INTERCEPTOR);
+        }
         if (isCache) {
             builder.addInterceptor(new CacheInterceptor(context))
 //                .addNetworkInterceptor(CacheInterceptor())

+ 9 - 0
okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpConfig.java

@@ -1,6 +1,7 @@
 package com.benyanyi.okhttp.type;
 
 import android.content.Context;
+
 import androidx.annotation.NonNull;
 
 import com.benyanyi.okhttp.util.OkHttpLog;
@@ -19,6 +20,14 @@ import okhttp3.logging.HttpLoggingInterceptor;
 class HttpConfig {
 
     static HttpLoggingInterceptor HTTP_LOGGING_INTERCEPTOR =
+            new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
+                @Override
+                public void log(@NonNull String message) {
+                    OkHttpLog.d(message);
+                }
+            }).setLevel(HttpLoggingInterceptor.Level.BODY);
+
+    static HttpLoggingInterceptor HTTP_LOGGING_INTERCEPTOR_FILE =
             new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                 @Override
                 public void log(@NonNull String message) {

+ 18 - 4
okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpRequest.java

@@ -157,25 +157,39 @@ public class HttpRequest implements RequestType {
                 .url(url)
                 .post(multipartBody)
                 .build();
-        return send();
+        return send(true);
     }
 
     @Override
     public DownloadConfig download() {
-        return new DownloadCall.Builder().setContext(context).setUrl(url).builder();
+        return new DownloadCall.Builder().setContext(context).setUrl(url).setCover(false).setSuffix("").builder();
+    }
+
+    @Override
+    public DownloadConfig download(boolean isCover) {
+        return new DownloadCall.Builder().setContext(context).setUrl(url).setCover(isCover).setSuffix("").builder();
     }
 
     @Override
     public DownloadConfig download(String suffix) {
-        return new DownloadCall.Builder().setContext(context).setUrl(url).setSuffix(suffix).builder();
+        return new DownloadCall.Builder().setContext(context).setUrl(url).setCover(false).setSuffix(suffix).builder();
+    }
+
+    @Override
+    public DownloadConfig download(boolean isCover, String suffix) {
+        return new DownloadCall.Builder().setContext(context).setUrl(url).setCover(isCover).setSuffix(suffix).builder();
     }
 
     private RequestConfig send() {
+        return send(false);
+    }
+
+    private RequestConfig send(boolean isFile) {
         return new HttpCall.Builder()
                 .setCache(isCache)
                 .setCacheUrl(mCacheName)
                 .setContext(context)
-                .setHttpClient(Client.getClient(context, isCache))
+                .setHttpClient(Client.getClient(context, isCache, isFile))
                 .setRequest(request)
                 .builder();
     }

+ 14 - 0
okhttplib/src/main/java/com/benyanyi/okhttp/type/RequestType.java

@@ -27,6 +27,20 @@ public interface RequestType {
 
     DownloadConfig download();
 
+    /**
+     * @param isCover 是否覆盖之前的文件
+     */
+    DownloadConfig download(boolean isCover);
+
+    /**
+     * @param suffix 文件名后缀
+     */
     DownloadConfig download(String suffix);
 
+    /**
+     * @param isCover 是否覆盖之前的文件
+     * @param suffix  文件名后缀
+     */
+    DownloadConfig download(boolean isCover, String suffix);
+
 }