Forráskód Böngészése

提交1.1.6版本,优化下载方法

yanyi 5 éve
szülő
commit
c094834330
22 módosított fájl, 200 hozzáadás és 637 törlés
  1. 3 1
      README.md
  2. 34 30
      app/src/main/java/com/mylove/okhttp/DownloadActivity.java
  3. 22 1
      app/src/main/java/com/mylove/okhttp/MainActivity.java
  4. 1 1
      okhttplib/bintrayUpload.gradle
  5. 3 3
      okhttplib/src/main/java/com/benyanyi/okhttp/OkHttpUtil.java
  6. 0 1
      okhttplib/src/main/java/com/benyanyi/okhttp/call/HttpCall.java
  7. 0 20
      okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadBean.java
  8. 0 214
      okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadObservable.java
  9. 0 60
      okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadRequest.java
  10. 0 94
      okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/FileUtil.java
  11. 59 0
      okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadCall.java
  12. 19 0
      okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadConfig.java
  13. 25 9
      okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadManager.java
  14. 0 169
      okhttplib/src/main/java/com/benyanyi/okhttp/download/NotificationUtil.java
  15. 4 2
      okhttplib/src/main/java/com/benyanyi/okhttp/listener/OnDownLoadObserver.java
  16. 0 14
      okhttplib/src/main/java/com/benyanyi/okhttp/listener/OnDownloadListener.java
  17. 6 3
      okhttplib/src/main/java/com/benyanyi/okhttp/type/CacheInterceptor.java
  18. 3 3
      okhttplib/src/main/java/com/benyanyi/okhttp/type/Client.java
  19. 5 5
      okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpConfig.java
  20. 9 3
      okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpRequest.java
  21. 3 0
      okhttplib/src/main/java/com/benyanyi/okhttp/type/RequestType.java
  22. 4 4
      okhttplib/src/main/java/com/benyanyi/okhttp/type/SslConfig.java

+ 3 - 1
README.md

@@ -4,9 +4,11 @@
 
 module 下添加
 
-    compile 'com.yanyi.benyanyi:okhttplib:1.1.4'
+    implementation 'com.yanyi.benyanyi:okhttplib:1.1.6'
     
 ### 更新记录
+* 2019-08-15(1.1.6) 优化下载方法,添加下载文件后缀添加方法
+* 2019-08-13(1.1.5) 重构代码,优化方法,使调用更简洁明了
 * 2019-07-19(1.1.4) 优化回调方法
 * 2019-06-14(1.1.3) 优化代码,更改包名,用于统一化开源库
 * 2019-03-06(1.1.2) 去除在线更新方法,将在线更新单独做开源库,去除多余下载方法,减少库大小

+ 34 - 30
app/src/main/java/com/mylove/okhttp/DownloadActivity.java

@@ -9,9 +9,9 @@ import android.widget.Button;
 import android.widget.ProgressBar;
 
 import com.benyanyi.loglib.Jlog;
-import com.benyanyi.okhttp.download.BaseDownLoadObserver;
+import com.benyanyi.okhttp.OkHttpUtil;
 import com.benyanyi.okhttp.download.DownloadInfo;
-import com.benyanyi.okhttp.download.DownloadManager;
+import com.benyanyi.okhttp.listener.OnDownLoadObserver;
 
 /**
  * @author BenYanYi
@@ -23,9 +23,6 @@ public class DownloadActivity extends AppCompatActivity implements View.OnClickL
     private Button downloadBtn1, downloadBtn2, downloadBtn3;
     private Button cancelBtn1, cancelBtn2, cancelBtn3;
     private ProgressBar progress1, progress2, progress3;
-    private String url1 = "http://www.yanyi.red/bluetooth/ios.pdf";
-    private String url2 = "http://www.yanyi.red/bluetooth/dectector/dectector.apk";
-    private String url3 = "http://www.yanyi.red/bluetooth/dectector/dfu_pkg1119.zip";
 
     private Context mContext;
 
@@ -34,32 +31,35 @@ public class DownloadActivity extends AppCompatActivity implements View.OnClickL
         super.onCreate(savedInstanceState);
         setContentView(R.layout.act_download);
         mContext = this;
-//        downloadBtn1 = bindView(R.id.main_btn_down1);
-//        downloadBtn2 = bindView(R.id.main_btn_down2);
-//        downloadBtn3 = bindView(R.id.main_btn_down3);
-//
-//        cancelBtn1 = bindView(R.id.main_btn_cancel1);
-//        cancelBtn2 = bindView(R.id.main_btn_cancel2);
-//        cancelBtn3 = bindView(R.id.main_btn_cancel3);
-//
-//        progress1 = bindView(R.id.main_progress1);
-//        progress2 = bindView(R.id.main_progress2);
-//        progress3 = bindView(R.id.main_progress3);
-//
-//        downloadBtn1.setOnClickListener(this);
-//        downloadBtn2.setOnClickListener(this);
-//        downloadBtn3.setOnClickListener(this);
-//
-//        cancelBtn1.setOnClickListener(this);
-//        cancelBtn2.setOnClickListener(this);
-//        cancelBtn3.setOnClickListener(this);
+        downloadBtn1 = bindView(R.id.main_btn_down1);
+        downloadBtn2 = bindView(R.id.main_btn_down2);
+        downloadBtn3 = bindView(R.id.main_btn_down3);
+
+        cancelBtn1 = bindView(R.id.main_btn_cancel1);
+        cancelBtn2 = bindView(R.id.main_btn_cancel2);
+        cancelBtn3 = bindView(R.id.main_btn_cancel3);
+
+        progress1 = bindView(R.id.main_progress1);
+        progress2 = bindView(R.id.main_progress2);
+        progress3 = bindView(R.id.main_progress3);
+
+        downloadBtn1.setOnClickListener(this);
+        downloadBtn2.setOnClickListener(this);
+        downloadBtn3.setOnClickListener(this);
+
+        cancelBtn1.setOnClickListener(this);
+        cancelBtn2.setOnClickListener(this);
+        cancelBtn3.setOnClickListener(this);
     }
 
     @Override
     public void onClick(View v) {
+        String url1 = "http://www.yanyi.red/bluetooth/ios.pdf";
+        String url2 = "http://www.yanyi.red/bluetooth/dectector/dectector.apk";
+        String url3 = "http://www.yanyi.red/bluetooth/dectector/dfu_pkg1119.zip";
         switch (v.getId()) {
             case R.id.main_btn_down1:
-                DownloadManager.getInstance(mContext).download(url1, new BaseDownLoadObserver() {
+                OkHttpUtil.getInstance(mContext).url(url1).download().start(new OnDownLoadObserver() {
                     @Override
                     public void onNext(DownloadInfo downloadInfo) {
                         super.onNext(downloadInfo);
@@ -75,10 +75,12 @@ public class DownloadActivity extends AppCompatActivity implements View.OnClickL
                 });
                 break;
             case R.id.main_btn_down2:
-                DownloadManager.getInstance(mContext).download(url2, new BaseDownLoadObserver() {
+                OkHttpUtil.getInstance(mContext).url(url2).download().start(new OnDownLoadObserver() {
                     @Override
                     public void onNext(DownloadInfo downloadInfo) {
                         Jlog.v(downloadInfo.getProgress());
+                        progress2.setMax((int) downloadInfo.getTotal());
+                        progress2.setProgress((int) downloadInfo.getProgress());
                     }
 
                     @Override
@@ -93,10 +95,12 @@ public class DownloadActivity extends AppCompatActivity implements View.OnClickL
                 });
                 break;
             case R.id.main_btn_down3:
-                DownloadManager.getInstance(mContext).download(url3, new BaseDownLoadObserver() {
+                OkHttpUtil.getInstance(mContext).url(url3).download().start(new OnDownLoadObserver() {
                     @Override
                     public void onNext(DownloadInfo downloadInfo) {
                         Jlog.v(downloadInfo.getProgress());
+                        progress3.setMax((int) downloadInfo.getTotal());
+                        progress3.setProgress((int) downloadInfo.getProgress());
                     }
 
                     @Override
@@ -111,13 +115,13 @@ public class DownloadActivity extends AppCompatActivity implements View.OnClickL
                 });
                 break;
             case R.id.main_btn_cancel1:
-                DownloadManager.getInstance(mContext).cancel(url1);
+                OkHttpUtil.getInstance(mContext).url(url1).download().cancel();
                 break;
             case R.id.main_btn_cancel2:
-                DownloadManager.getInstance(mContext).cancel(url2);
+                OkHttpUtil.getInstance(mContext).url(url2).download().cancel();
                 break;
             case R.id.main_btn_cancel3:
-                DownloadManager.getInstance(mContext).cancel(url3);
+                OkHttpUtil.getInstance(mContext).url(url3).download().cancel();
                 break;
             default:
                 break;

+ 22 - 1
app/src/main/java/com/mylove/okhttp/MainActivity.java

@@ -1,5 +1,6 @@
 package com.mylove.okhttp;
 
+import android.content.Intent;
 import android.os.Bundle;
 import android.support.annotation.Nullable;
 import android.support.v7.app.AppCompatActivity;
@@ -7,6 +8,10 @@ import android.support.v7.app.AppCompatActivity;
 import com.benyanyi.loglib.Jlog;
 import com.benyanyi.okhttp.OkHttpUtil;
 import com.benyanyi.okhttp.listener.OnOkHttpListener;
+import com.benyanyi.permissionlib.PermissionCallBack;
+import com.benyanyi.permissionlib.PermissionHelper;
+import com.benyanyi.permissionlib.PermissionType;
+import com.benyanyi.permissionlib.msg.FailureMsg;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -27,7 +32,23 @@ public class MainActivity extends AppCompatActivity {
 //        setContentView(R.layout.notification_contentview);
         setContentView(R.layout.activity_main);
         init();
-//        String[] strings = new String[]{PermissionType.STORAGE};
+        String[] strings = new String[]{PermissionType.STORAGE};
+        PermissionHelper.getInstance(this).hasPermission(1, new PermissionCallBack() {
+            @Override
+            public void onPermissionSuccess(int permissionCode) {
+                startActivity(new Intent(MainActivity.this, DownloadActivity.class));
+            }
+
+            @Override
+            public void onPermissionFailure(FailureMsg failureMsg) {
+
+            }
+
+            @Override
+            public void onPermissionComplete(int permissionCode) {
+
+            }
+        }, strings);
 //        permissionHelper = new PermissionHelper(this, strings);
 //        permissionHelper.hasPermission(new PermissionHelper.OnPermissionListener() {
 //            @Override

+ 1 - 1
okhttplib/bintrayUpload.gradle

@@ -7,7 +7,7 @@ def siteUrl = 'http://www.yanyis.space/yanyi/baseokhttp' // 项目主页。
 def gitUrl = 'http://www.yanyis.space/yanyi/baseokhttp.git' // Git仓库的url。
 
 group = "com.yanyi.benyanyi"// 唯一包名,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的com.ansen.http就是这里配置的。
-version = "1.1.5" //项目引用的版本号,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的1.0.1就是这里配置的。
+version = "1.1.6" //项目引用的版本号,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的1.0.1就是这里配置的。
 install {
     repositories.mavenInstaller {
         // This generates POM.xml with proper parameters

+ 3 - 3
okhttplib/src/main/java/com/benyanyi/okhttp/OkHttpUtil.java

@@ -2,7 +2,7 @@ package com.benyanyi.okhttp;
 
 import android.content.Context;
 
-import com.benyanyi.okhttp.type.CallType;
+import com.benyanyi.okhttp.type.HttpRequest;
 import com.benyanyi.okhttp.type.RequestType;
 
 /**
@@ -25,11 +25,11 @@ public class OkHttpUtil {
     }
 
     public RequestType url(String url) {
-        return new CallType(mContext, url, false);
+        return new HttpRequest(mContext, url, false);
     }
 
     public RequestType url(String url, boolean isCache) {
-        return new CallType(mContext, url, isCache);
+        return new HttpRequest(mContext, url, isCache);
     }
 
 }

+ 0 - 1
okhttplib/src/main/java/com/benyanyi/okhttp/call/HttpCall.java

@@ -60,7 +60,6 @@ public class HttpCall implements RequestConfig {
         this.builder.setCallType(CallType.SYNC).builder().send(onOkHttpListener);
     }
 
-
     public static class Builder {
 
         private Context context;

+ 0 - 20
okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadBean.java

@@ -1,20 +0,0 @@
-package com.benyanyi.okhttp.deprecated;
-
-/**
- * @author BenYanYi
- * @date 2018/9/12 15:32
- * @email ben@yanyi.red
- * @overview 下载状态
- */
-class DownloadBean {
-    public int status = 0;
-    public String filePath;
-
-    @Override
-    public String toString() {
-        return "DownloadBean{" +
-                ", status=" + status +
-                ", filePath='" + filePath + '\'' +
-                '}';
-    }
-}

+ 0 - 214
okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadObservable.java

@@ -1,214 +0,0 @@
-package com.benyanyi.okhttp.deprecated;
-
-import android.annotation.SuppressLint;
-import android.content.Context;
-import android.support.annotation.NonNull;
-
-import com.benyanyi.okhttp.config.CacheInterceptor;
-import com.benyanyi.okhttp.config.HttpConfig;
-import com.benyanyi.okhttp.config.SslConfig;
-import com.benyanyi.okhttp.util.FormatUtil;
-import com.benyanyi.okhttp.util.Internet;
-import com.benyanyi.okhttp.util.InternetBean;
-import com.benyanyi.okhttp.util.OkHttpLog;
-import com.benyanyi.okhttp.listener.OnDownloadListener;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.concurrent.TimeUnit;
-
-import io.reactivex.Observable;
-import io.reactivex.ObservableEmitter;
-import io.reactivex.ObservableOnSubscribe;
-import io.reactivex.Observer;
-import io.reactivex.android.schedulers.AndroidSchedulers;
-import io.reactivex.disposables.Disposable;
-import io.reactivex.schedulers.Schedulers;
-import okhttp3.Call;
-import okhttp3.Callback;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.Response;
-
-/**
- * @author myLove
- */
-
-class DownloadObservable {
-    @SuppressLint("StaticFieldLeak")
-    private static DownloadObservable instance;
-    @SuppressLint("StaticFieldLeak")
-    private static Context mContext;
-    private String filePath;
-    private String fileName;
-    private static OkHttpClient okHttpClient;
-
-    private DownloadObservable() {
-    }
-
-    static DownloadObservable getInstance(Context context) {
-        if (instance == null) {
-            synchronized (DownloadObservable.class) {
-                if (instance == null) {
-                    instance = new DownloadObservable();
-                    OkHttpClient httpClient = new OkHttpClient();
-
-                    okHttpClient = httpClient.newBuilder()
-                            .addNetworkInterceptor(new CacheInterceptor(context))
-                            .addInterceptor(HttpConfig.HTTP_LOGGING_INTERCEPTOR)
-                            .cache(HttpConfig.privateCache(context))
-                            .connectTimeout(30, TimeUnit.SECONDS)
-                            .readTimeout(30, TimeUnit.SECONDS)
-                            .writeTimeout(30, TimeUnit.SECONDS)
-                            //支持HTTPS请求,跳过证书验证
-                            .sslSocketFactory(SslConfig.createSSLSocketFactory(), SslConfig.getTrustManager())
-                            .build();
-                }
-            }
-        }
-        mContext = context;
-        return instance;
-    }
-
-    void request(String url, String filePath, String fileName, final OnDownloadListener onDownloadListener) {
-        this.filePath = filePath;
-        this.fileName = fileName;
-        getObservable(url)
-                .subscribeOn(Schedulers.io())
-                .observeOn(AndroidSchedulers.mainThread())
-                .subscribe(new Observer<DownloadBean>() {
-                    @Override
-                    public void onSubscribe(Disposable d) {
-
-                    }
-
-                    @Override
-                    public void onNext(DownloadBean bean) {
-                        OkHttpLog.d(bean);
-                        if (bean.status == 1) {
-                            onDownloadListener.onSuccess(bean.filePath);
-                        } else {
-                            onDownloadListener.onDownloading();
-                        }
-                    }
-
-                    @Override
-                    public void onError(Throwable e) {
-                        OkHttpLog.e(e.getMessage());
-                        onDownloadListener.onFailure(e);
-                    }
-
-                    @Override
-                    public void onComplete() {
-                        OkHttpLog.d("********");
-
-                        onDownloadListener.onCompleted();
-                    }
-                });
-    }
-
-    private Observable<DownloadBean> getObservable(final String url) {
-        return Observable.create(new ObservableOnSubscribe<DownloadBean>() {
-            @Override
-            public void subscribe(ObservableEmitter<DownloadBean> e) {
-                send(url, e);
-            }
-        });
-    }
-
-    private void send(final String url, ObservableEmitter<DownloadBean> subscriber) {
-        InternetBean bean = Internet.ifInternet(mContext);
-        if (bean.getStatus()) {
-            Request request = new Request.Builder()
-                    .url(url)
-                    .build();
-            Call call = okHttpClient.newCall(request);
-            sendCall(url, call, subscriber);
-        } else {
-            subscriber.onError(new Exception(bean.getMsg()));
-        }
-    }
-
-    /**
-     * 请求
-     */
-    private void sendCall(final String url, Call call, final ObservableEmitter<DownloadBean> subscriber) {
-        call.enqueue(new Callback() {
-            @Override
-            public void onFailure(@NonNull Call call, @NonNull IOException e) {
-                OkHttpLog.e(e.getMessage());
-
-                subscriber.onError(e);
-                subscriber.onComplete();
-            }
-
-            @Override
-            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
-                callResponse(url, response, subscriber);
-            }
-        });
-    }
-
-    private void callResponse(String url, Response response, ObservableEmitter<DownloadBean> subscriber) throws IOException {
-        DownloadBean bean = new DownloadBean();
-        InputStream is = null;
-        byte[] buf = new byte[2048];
-        int len = 0;
-        FileOutputStream fos = null;
-        // 储存下载文件的目录
-        String savePath = FileUtil.isExistDir(filePath);
-        try {
-            is = response.body().byteStream();
-            long total = response.body().contentLength();
-            File file;
-            if (FormatUtil.isEmpty(fileName)) {
-                file = new File(savePath, FileUtil.getNameFromUrl(url));
-            } else {
-                file = new File(savePath, fileName);
-            }
-            bean.filePath = file.getAbsolutePath();
-            OkHttpLog.d(filePath);
-            fos = new FileOutputStream(file);
-            long sum = 0;
-            while ((len = is.read(buf)) != -1) {
-                fos.write(buf, 0, len);
-                sum += len;
-                bean.status = 0;
-                OkHttpLog.d(bean);
-                // 下载中
-                subscriber.onNext(bean);
-            }
-            fos.flush();
-            // 下载完成
-            bean.status = 1;
-            OkHttpLog.d(bean);
-
-            subscriber.onNext(bean);
-            subscriber.onComplete();
-        } catch (Exception e) {
-            OkHttpLog.e(e.getMessage());
-            subscriber.onError(e);
-            subscriber.onComplete();
-        } finally {
-            try {
-                if (is != null) {
-                    is.close();
-                }
-            } catch (IOException e) {
-                OkHttpLog.e(e.getMessage());
-
-            }
-            try {
-                if (fos != null) {
-                    fos.close();
-                }
-            } catch (IOException e) {
-                OkHttpLog.e(e.getMessage());
-
-            }
-        }
-    }
-
-}

+ 0 - 60
okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/DownloadRequest.java

@@ -1,60 +0,0 @@
-package com.benyanyi.okhttp.deprecated;
-
-import android.annotation.SuppressLint;
-import android.content.Context;
-
-import com.benyanyi.okhttp.listener.OnDownloadListener;
-import com.benyanyi.okhttp.util.FormatUtil;
-
-/**
- * @author myLove
- */
-
-class DownloadRequest {
-    @SuppressLint("StaticFieldLeak")
-    private static DownloadRequest instance;
-    private static String url;
-    @SuppressLint("StaticFieldLeak")
-    private static Context mContext;
-
-    public static DownloadRequest getInstance(Context context, String str) {
-        if (instance == null) {
-            synchronized (DownloadRequest.class) {
-                if (instance == null) {
-                    instance = new DownloadRequest();
-                }
-            }
-        }
-        mContext = context;
-        url = str;
-        return instance;
-    }
-
-    /**
-     * @param filePath           储存下载文件的SDCard目录
-     * @param onDownloadListener 监听
-     */
-    @Deprecated
-    void download(String filePath, OnDownloadListener onDownloadListener) {
-        //saveDir判断不能为空
-        if (FormatUtil.isEmpty(filePath)) {
-            throw new NullPointerException("filePath is the SDCard directory of the downloaded file, cannot be empty.");
-        }
-        DownloadObservable.getInstance(mContext).request(url, filePath, "", onDownloadListener);
-    }
-
-    /**
-     * @param filePath           储存下载文件的SDCard目录
-     * @param fileName           文件名称
-     * @param onDownloadListener 监听
-     */
-    @Deprecated
-    void download(String filePath, String fileName, OnDownloadListener onDownloadListener) {
-        //saveDir判断不能为空
-        if (FormatUtil.isEmpty(filePath)) {
-            throw new NullPointerException("filePath is the SDCard directory of the downloaded file, cannot be empty.");
-        }
-        DownloadObservable.getInstance(mContext).request(url, filePath, fileName, onDownloadListener);
-    }
-
-}

+ 0 - 94
okhttplib/src/main/java/com/benyanyi/okhttp/deprecated/FileUtil.java

@@ -1,94 +0,0 @@
-package com.benyanyi.okhttp.deprecated;
-
-import android.graphics.Bitmap;
-import android.os.Environment;
-import android.support.annotation.NonNull;
-
-import com.benyanyi.okhttp.util.FormatUtil;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/**
- * @author myLove
- */
-
-class FileUtil {
-    /**
-     * @param saveDir
-     * @return
-     * @throws IOException 判断下载目录是否存在
-     */
-    static String isExistDir(String saveDir) throws IOException {
-        // 下载位置
-        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
-        if (!downloadFile.mkdirs()) {
-            downloadFile.createNewFile();
-        }
-        String savePath = downloadFile.getAbsolutePath();
-        return savePath;
-    }
-
-    /**
-     * 图片保存
-     */
-    static String saveImage(Bitmap bitmap, String path) {
-        File file = new File(path);
-        try {
-            if (!file.exists()) {
-                file.createNewFile();
-            }
-            FileOutputStream fos = new FileOutputStream(file);
-            String substring = path.substring(path.length() - 3, path.length());
-            if ("png".equals(substring)) {
-                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
-            } else {
-                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
-            }
-            fos.flush();
-            fos.close();
-        } catch (Exception e) {
-            e.fillInStackTrace();
-        }
-        return path;
-    }
-
-    static String getSDPath() {
-        File sdDir = null;
-        boolean sdCardExist = Environment.getExternalStorageState()
-                //判断sd卡是否存在
-                .equals(Environment.MEDIA_MOUNTED);
-        //判断sd卡是否存在
-        if (sdCardExist) {
-            //获取跟目录
-            sdDir = Environment.getExternalStorageDirectory();
-        }
-        return sdDir.toString();
-    }
-
-    /**
-     * @param url
-     * @return 从下载连接中解析出文件名
-     */
-    @NonNull
-    static String getNameFromUrl(String url) {
-        return url.substring(url.lastIndexOf("/") + 1);
-    }
-
-    /**
-     * 判断当前url下载的文件是否为自己所需的
-     *
-     * @param url
-     * @param condition 判断条件
-     * @return
-     */
-    static boolean ifUrl(String url, String condition) {
-        String str = url.substring(url.lastIndexOf("."));
-        if (FormatUtil.isNotEmpty(str)) {
-            return str.equals(condition);
-        } else {
-            return false;
-        }
-    }
-}

+ 59 - 0
okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadCall.java

@@ -0,0 +1,59 @@
+package com.benyanyi.okhttp.download;
+
+import android.content.Context;
+
+import com.benyanyi.okhttp.listener.OnDownLoadObserver;
+
+/**
+ * @author YanYi
+ * @date 2019-08-15 10:23
+ * @email ben@yanyi.red
+ * @overview
+ */
+public class DownloadCall implements DownloadConfig {
+
+    private Context mContext;
+    private String url;
+
+    private DownloadCall(Builder builder) {
+        this.mContext = builder.mContext;
+        this.url = builder.url;
+    }
+
+    @Override
+    public void start(OnDownLoadObserver onDownLoadObserver) {
+        DownloadManager.getInstance(mContext).download(url, onDownLoadObserver);
+    }
+
+    @Override
+    public void start(String suffix, OnDownLoadObserver onDownLoadObserver) {
+        DownloadManager.getInstance(mContext).download(url, suffix, onDownLoadObserver);
+    }
+
+    @Override
+    public void cancel() {
+        DownloadManager.getInstance(mContext).cancel(url);
+    }
+
+    public static class Builder {
+
+        private Context mContext;
+        private String url;
+
+        public Builder setContext(Context mContext) {
+            this.mContext = mContext;
+            return this;
+        }
+
+        public Builder setUrl(String url) {
+            this.url = url;
+            return this;
+        }
+
+        public DownloadConfig builder() {
+            return new DownloadCall(this);
+        }
+
+    }
+
+}

+ 19 - 0
okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadConfig.java

@@ -0,0 +1,19 @@
+package com.benyanyi.okhttp.download;
+
+import com.benyanyi.okhttp.listener.OnDownLoadObserver;
+
+/**
+ * @author YanYi
+ * @date 2019-08-15 10:25
+ * @email ben@yanyi.red
+ * @overview
+ */
+public interface DownloadConfig {
+
+    void start(OnDownLoadObserver onDownLoadObserver);
+
+    void start(String suffix, OnDownLoadObserver onDownLoadObserver);
+
+    void cancel();
+
+}

+ 25 - 9
okhttplib/src/main/java/com/benyanyi/okhttp/download/DownloadManager.java

@@ -3,6 +3,8 @@ package com.benyanyi.okhttp.download;
 import android.content.Context;
 
 
+import com.benyanyi.okhttp.listener.OnDownLoadObserver;
+
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -29,7 +31,7 @@ import okhttp3.Response;
  * @email ben@yanyi.red
  * @overview
  */
-public class DownloadManager {
+class DownloadManager {
     private static final AtomicReference<DownloadManager> INSTANCE = new AtomicReference<>();
     /**
      * 用来存放各个下载的请求
@@ -41,6 +43,8 @@ public class DownloadManager {
     private OkHttpClient mClient;
     private Context mContext;
 
+    private String suffix = "";//文件名后缀
+
     /**
      * 获得一个单例类
      *
@@ -69,10 +73,22 @@ public class DownloadManager {
     /**
      * 开始下载
      *
-     * @param url                  下载请求的网址
-     * @param baseDownLoadObserver 用来回调的接口
+     * @param suffix             文件名后缀
+     * @param url                下载请求的网址
+     * @param onDownLoadObserver 用来回调的接口
+     */
+    void download(String url, String suffix, OnDownLoadObserver onDownLoadObserver) {
+        this.suffix = suffix;
+        this.download(url, onDownLoadObserver);
+    }
+
+    /**
+     * 开始下载
+     *
+     * @param url                下载请求的网址
+     * @param onDownLoadObserver 用来回调的接口
      */
-    public void download(String url, BaseDownLoadObserver baseDownLoadObserver) {
+    void download(String url, OnDownLoadObserver onDownLoadObserver) {
         Observable.just(url)
                 //call的map已经有了,就证明正在下载,则这次不下载
                 .filter(new Predicate<String>() {
@@ -106,11 +122,11 @@ public class DownloadManager {
                 //在子线程执行
                 .subscribeOn(Schedulers.io())
                 //添加观察者
-                .subscribe(baseDownLoadObserver);
+                .subscribe(onDownLoadObserver);
 
     }
 
-    public void cancel(String url) {
+    void cancel(String url) {
         Call call = downCalls.get(url);
         if (call != null) {
             call.cancel();//取消
@@ -129,7 +145,7 @@ public class DownloadManager {
         //获得文件大小
         long contentLength = getContentLength(url);
         downloadInfo.setTotal(contentLength);
-        String fileName = url.substring(url.lastIndexOf("/"));
+        String fileName = url.substring(url.lastIndexOf("/")) + suffix;
         downloadInfo.setFileName(fileName);
         return downloadInfo;
     }
@@ -154,7 +170,7 @@ public class DownloadManager {
                 fileNameOther = fileName.substring(0, dotIndex)
                         + "(" + i + ")" + fileName.substring(dotIndex);
             }
-            File newFile = new File(savePath, fileNameOther);
+            File newFile = new File(savePath, fileNameOther + suffix);
             file = newFile;
             downloadLength = newFile.length();
             i++;
@@ -169,7 +185,7 @@ public class DownloadManager {
     private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
         private DownloadInfo downloadInfo;
 
-        public DownloadSubscribe(DownloadInfo downloadInfo) {
+        DownloadSubscribe(DownloadInfo downloadInfo) {
             this.downloadInfo = downloadInfo;
         }
 

+ 0 - 169
okhttplib/src/main/java/com/benyanyi/okhttp/download/NotificationUtil.java

@@ -1,169 +0,0 @@
-package com.benyanyi.okhttp.download;
-
-import android.app.Activity;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.Color;
-import android.os.Build;
-import android.widget.RemoteViews;
-
-import com.benyanyi.okhttp.R;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author BenYanYi
- * @date 2018/11/20 15:51
- * @email ben@yanyi.red
- * @overview
- */
-public class NotificationUtil {
-    /**
-     * NotificationManager : 是状态栏通知的管理类,负责发通知、清楚通知等。
-     */
-    private NotificationManager manager;
-    /**
-     * 定义Map来保存Notification对象
-     */
-    private Map<Integer, Notification> map = null;
-    private int icon;
-    private Class<?> aClass;
-    private boolean isCreateChannel = false;
-    private static final String NOTIFICATION_CHANNEL_NAME = "Update";
-    private NotificationManager notificationManager = null;
-    private Activity mActivity;
-    private String title;
-
-    public NotificationUtil(Activity activity, int icon, String title) {
-        this.mActivity = activity;
-        this.icon = icon;
-        this.title = title;
-        // NotificationManager 是一个系统Service,必须通过 getSystemService()方法来获取。
-        manager = (NotificationManager) mActivity
-                .getSystemService(Context.NOTIFICATION_SERVICE);
-        map = new HashMap<>();
-    }
-
-    public NotificationUtil setIcon(int icon) {
-        this.icon = icon;
-        return this;
-    }
-
-    public void setTitle(String title) {
-        this.title = title;
-    }
-
-    public NotificationUtil setClass(Class<?> aClass) {
-        this.aClass = aClass;
-        return this;
-    }
-
-    public void showNotification(int notificationId) {
-        // 判断对应id的Notification是否已经显示, 以免同一个Notification出现多次
-        if (!map.containsKey(notificationId)) {
-            // 创建通知对象
-            Notification notification;
-            Notification.Builder builder;
-            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
-                //Android O上对Notification进行了修改,如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
-                if (null == notificationManager) {
-                    notificationManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
-                }
-                String channelId = mActivity.getPackageName();
-                if (!isCreateChannel) {
-                    NotificationChannel notificationChannel = new NotificationChannel(channelId,
-                            NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
-                    //是否在桌面icon右上角展示小圆点
-                    notificationChannel.enableLights(true);
-                    //小圆点颜色
-                    notificationChannel.setLightColor(Color.BLUE);
-                    //是否在久按桌面图标时显示此渠道的通知
-                    notificationChannel.setShowBadge(true);
-                    notificationManager.createNotificationChannel(notificationChannel);
-                    isCreateChannel = true;
-                }
-                builder = new Notification.Builder(mActivity.getApplicationContext(), channelId);
-                builder.setSmallIcon(icon);
-                builder.setTimeoutAfter(System.currentTimeMillis());
-                if (aClass != null) {
-                    Intent in = new Intent(mActivity, aClass);
-                    builder.setContentIntent(PendingIntent.getActivity(mActivity, 0, in, 0));
-                }
-                builder.setCustomContentView(new RemoteViews(
-                        mActivity.getPackageName(),
-                        R.layout.notification_contentview));
-                RemoteViews contentView = builder.createContentView();
-                contentView.setTextViewText(R.id.title, title);
-                contentView.setImageViewResource(R.id.icon, icon);
-                notification = builder.build();
-            } else {
-                notification = new Notification();
-                // 设置显示时间
-                notification.when = System.currentTimeMillis();
-                // 设置通知显示的图标
-                notification.icon = icon;
-                // 设置通知的特性: 通知被点击后,自动消失
-                notification.flags = Notification.FLAG_AUTO_CANCEL;
-                // 设置点击通知栏操作
-                if (aClass != null) {
-                    // 点击跳转到指定页面
-                    Intent in = new Intent(mActivity, aClass);
-                    notification.contentIntent = PendingIntent.getActivity(mActivity, 0, in,
-                            0);
-                }
-                // 设置通知的显示视图
-                notification.contentView = new RemoteViews(
-                        mActivity.getPackageName(),
-                        R.layout.notification_contentview);
-                notification.contentView.setTextViewText(R.id.title, title);
-                notification.contentView.setImageViewResource(R.id.icon, icon);
-            }
-            // 发出通知
-            manager.notify(notificationId, notification);
-            // 存入Map中
-            map.put(notificationId, notification);
-        }
-    }
-
-    /**
-     * 取消通知操作
-     */
-    public void cancel(int notificationId) {
-        manager.cancel(notificationId);
-        map.remove(notificationId);
-    }
-
-    public void updateProgressText(int notificationId, int progress) {
-        Notification notify = map.get(notificationId);
-        if (null != notify) {
-            // 修改进度条
-            notify.contentView.setProgressBar(R.id.pBar, 100, progress, false);
-            manager.notify(notificationId, notify);
-        }
-    }
-
-    public void tickerText(int notificationId, String text) {
-        Notification notify = map.get(notificationId);
-        if (null != notify) {
-            // 修改进度条
-            notify.contentView.setTextViewText(R.id.title, title);
-            manager.notify(notificationId, notify);
-        }
-    }
-
-    public void updateProgressText(int notificationId, int progress, String text) {
-        Notification notify = map.get(notificationId);
-        if (null != notify) {
-            notify.contentView.setTextViewText(R.id.title, text);
-            // 修改进度条
-            notify.contentView.setProgressBar(R.id.pBar, 100, progress, false);
-            manager.notify(notificationId, notify);
-        }
-    }
-
-}

+ 4 - 2
okhttplib/src/main/java/com/benyanyi/okhttp/download/BaseDownLoadObserver.java → okhttplib/src/main/java/com/benyanyi/okhttp/listener/OnDownLoadObserver.java

@@ -1,4 +1,6 @@
-package com.benyanyi.okhttp.download;
+package com.benyanyi.okhttp.listener;
+
+import com.benyanyi.okhttp.download.DownloadInfo;
 
 import io.reactivex.Observer;
 import io.reactivex.disposables.Disposable;
@@ -9,7 +11,7 @@ import io.reactivex.disposables.Disposable;
  * @email ben@yanyi.red
  * @overview
  */
-public abstract class BaseDownLoadObserver implements Observer<DownloadInfo> {
+public abstract class OnDownLoadObserver implements Observer<DownloadInfo> {
     /**
      * 可以用于取消注册的监听者
      */

+ 0 - 14
okhttplib/src/main/java/com/benyanyi/okhttp/listener/OnDownloadListener.java

@@ -1,14 +0,0 @@
-package com.benyanyi.okhttp.listener;
-
-/**
- * @author BenYanYi
- * @date 2018/9/11 11:27
- * @email ben@yanyi.red
- * @overview
- */
-public interface OnDownloadListener extends OnOkHttpListener {
-    /**
-     * 下载中
-     */
-    void onDownloading();
-}

+ 6 - 3
okhttplib/src/main/java/com/benyanyi/okhttp/config/CacheInterceptor.java → okhttplib/src/main/java/com/benyanyi/okhttp/type/CacheInterceptor.java

@@ -1,10 +1,12 @@
-package com.benyanyi.okhttp.config;
+package com.benyanyi.okhttp.type;
 
 
 import android.content.Context;
 
 import com.benyanyi.okhttp.util.InternetUtil;
 
+import org.jetbrains.annotations.NotNull;
+
 import java.io.IOException;
 
 import okhttp3.CacheControl;
@@ -18,14 +20,15 @@ import okhttp3.Response;
  * @email ben@yanyi.red
  * @overview
  */
-public class CacheInterceptor implements Interceptor {
+class CacheInterceptor implements Interceptor {
 
     private Context context;
 
-    public CacheInterceptor(Context context) {
+    CacheInterceptor(Context context) {
         this.context = context;
     }
 
+    @NotNull
     @Override
     public Response intercept(Chain chain) throws IOException {
 

+ 3 - 3
okhttplib/src/main/java/com/benyanyi/okhttp/config/Client.java → okhttplib/src/main/java/com/benyanyi/okhttp/type/Client.java

@@ -1,4 +1,4 @@
-package com.benyanyi.okhttp.config;
+package com.benyanyi.okhttp.type;
 
 import android.content.Context;
 
@@ -12,9 +12,9 @@ import okhttp3.OkHttpClient;
  * @email ben@yanyi.red
  * @overview
  */
-public class Client {
+class Client {
 
-    public static OkHttpClient getClient(Context context, boolean isCache) {
+    static OkHttpClient getClient(Context context, boolean isCache) {
         OkHttpClient.Builder builder = new OkHttpClient.Builder();
         builder.addNetworkInterceptor(HttpConfig.HTTP_LOGGING_INTERCEPTOR);
         if (isCache) {

+ 5 - 5
okhttplib/src/main/java/com/benyanyi/okhttp/config/HttpConfig.java → okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpConfig.java

@@ -1,4 +1,4 @@
-package com.benyanyi.okhttp.config;
+package com.benyanyi.okhttp.type;
 
 import android.content.Context;
 import android.support.annotation.NonNull;
@@ -16,9 +16,9 @@ import okhttp3.logging.HttpLoggingInterceptor;
  * @email ben@yanyi.red
  * @overview
  */
-public class HttpConfig {
+class HttpConfig {
 
-    public static HttpLoggingInterceptor HTTP_LOGGING_INTERCEPTOR =
+    static HttpLoggingInterceptor HTTP_LOGGING_INTERCEPTOR =
             new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                 @Override
                 public void log(@NonNull String message) {
@@ -29,7 +29,7 @@ public class HttpConfig {
     /**
      * 设置缓存路径,以及缓存文件大小
      */
-    public static okhttp3.Cache privateCache(Context mContext) {
+    static okhttp3.Cache privateCache(Context mContext) {
         return new okhttp3.Cache(mContext.getCacheDir(), 1024 * 1024);
     }
 //    fun verifier(): HostnameVerifier
@@ -39,7 +39,7 @@ public class HttpConfig {
 //
 //    }
 
-    public static HostnameVerifier verifier() {
+    static HostnameVerifier verifier() {
         return new HostnameVerifier() {
             @Override
             public boolean verify(String hostname, SSLSession session) {

+ 9 - 3
okhttplib/src/main/java/com/benyanyi/okhttp/type/CallType.java → okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpRequest.java

@@ -2,7 +2,8 @@ package com.benyanyi.okhttp.type;
 
 import android.content.Context;
 
-import com.benyanyi.okhttp.config.Client;
+import com.benyanyi.okhttp.download.DownloadCall;
+import com.benyanyi.okhttp.download.DownloadConfig;
 import com.benyanyi.okhttp.call.HttpCall;
 import com.benyanyi.okhttp.call.RequestConfig;
 import com.benyanyi.okhttp.util.FormatUtil;
@@ -24,7 +25,7 @@ import okhttp3.RequestBody;
  * @email ben@yanyi.red
  * @overview
  */
-public class CallType implements RequestType {
+public class HttpRequest implements RequestType {
 
     private Context context;
     private boolean isCache;
@@ -32,7 +33,7 @@ public class CallType implements RequestType {
     private String mCacheName;
     private Request request;
 
-    public CallType(Context context, String url, boolean isCache) {
+    public HttpRequest(Context context, String url, boolean isCache) {
         this.context = context;
         this.url = url;
         this.isCache = isCache;
@@ -152,6 +153,11 @@ public class CallType implements RequestType {
         return send();
     }
 
+    @Override
+    public DownloadConfig download() {
+        return new DownloadCall.Builder().setContext(context).setUrl(url).builder();
+    }
+
     private RequestConfig send() {
         return new HttpCall.Builder()
                 .setCache(isCache)

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

@@ -1,5 +1,6 @@
 package com.benyanyi.okhttp.type;
 
+import com.benyanyi.okhttp.download.DownloadConfig;
 import com.benyanyi.okhttp.call.RequestConfig;
 
 import java.util.Map;
@@ -24,4 +25,6 @@ public interface RequestType {
 
     RequestConfig file(Map<Object, Object> map);
 
+    DownloadConfig download();
+
 }

+ 4 - 4
okhttplib/src/main/java/com/benyanyi/okhttp/config/SslConfig.java → okhttplib/src/main/java/com/benyanyi/okhttp/type/SslConfig.java

@@ -1,4 +1,4 @@
-package com.benyanyi.okhttp.config;
+package com.benyanyi.okhttp.type;
 
 import java.security.SecureRandom;
 import java.security.cert.CertificateException;
@@ -15,7 +15,7 @@ import javax.net.ssl.X509TrustManager;
  * @email ben@yanyi.red
  * @overview
  */
-public class SslConfig {
+class SslConfig {
     /**
      * 生成安全套接字工厂,用于https请求的证书跳过
      * <p>
@@ -29,7 +29,7 @@ public class SslConfig {
      *
      * @return
      */
-    public static SSLSocketFactory createSSLSocketFactory() {
+    static SSLSocketFactory createSSLSocketFactory() {
 
         SSLSocketFactory sslSocketFactory = null;
         try {
@@ -42,7 +42,7 @@ public class SslConfig {
         return sslSocketFactory;
     }
 
-    public static X509TrustManager getTrustManager() {
+    static X509TrustManager getTrustManager() {
         return new X509TrustManager() {
             @Override
             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {