瀏覽代碼

添加不带进度的文件下载方法

YanYi 7 年之前
父節點
當前提交
7f51adae50

+ 1 - 1
README.md

@@ -4,7 +4,7 @@
 
 module 下添加
 
-     compile 'com.github.love-yanyi:OkHttp:1.0.4'
+     compile 'com.github.love-yanyi:OkHttp:1.0.5'
 
 <br/>
 project 下添加

+ 2 - 1
app/build.gradle

@@ -4,7 +4,7 @@ android {
     compileSdkVersion 26
     defaultConfig {
         applicationId "com.mylove.okhttp"
-        minSdkVersion 14
+        minSdkVersion 15
         targetSdkVersion 26
         versionCode 1
         versionName "1.0"
@@ -32,4 +32,5 @@ dependencies {
     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
     compile project(':okhttp2')
     implementation 'com.github.love-yanyi:Logger:1.0.1'
+    implementation 'com.didikee:permissionsHelper:0.1.8'
 }

+ 7 - 0
app/src/main/AndroidManifest.xml

@@ -1,6 +1,13 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.mylove.okhttp">
 
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <!--STORAGE-->
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
     <application
         android:name=".AppContext"
         android:allowBackup="true"

+ 87 - 9
app/src/main/java/com/mylove/okhttp/MainActivity.java

@@ -1,14 +1,15 @@
 package com.mylove.okhttp;
 
+import android.content.Intent;
 import android.os.Bundle;
-import android.os.PersistableBundle;
+import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.v7.app.AppCompatActivity;
 
 import com.mylove.loglib.JLog;
 
-import java.util.HashMap;
-import java.util.Map;
+import didikee.com.permissionshelper.PermissionsHelper;
+import didikee.com.permissionshelper.permission.DangerousPermissions;
 
 
 /**
@@ -19,15 +20,65 @@ import java.util.Map;
  */
 
 public class MainActivity extends AppCompatActivity {
+
+    // app所需要的全部危险权限
+    static final String[] PERMISSIONS = new String[]{DangerousPermissions.STORAGE};
+    private PermissionsHelper permissionsHelper;
+
     @Override
-    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
-        super.onCreate(savedInstanceState, persistentState);
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
-        String url = "https://www.yjw1020.club/api/myIndex.php";
-        Map<Object, Object> oMap = new HashMap<>();
-        oMap.put("type", "1");
-        OkHttpUtil.getInstance(this).post(url).async(oMap, new onOkHttpListener<String, String>() {
+        setPermissions();
+    }
+
+    private void setPermissions(){
+        permissionsHelper = new PermissionsHelper(this, PERMISSIONS, true);
+        if (permissionsHelper.checkAllPermissions(PERMISSIONS)) {
+            permissionsHelper.onDestroy();
+            data();
+        } else {
+            //申请权限
+            permissionsHelper.startRequestNeedPermissions();
+        }
+        permissionsHelper.setonAllNeedPermissionsGrantedListener(new PermissionsHelper.onAllNeedPermissionsGrantedListener() {
+            //全部许可了,已经获得了所有权限
+            @Override
+            public void onAllNeedPermissionsGranted() {
+                //做原先的业务代码
+                JLog.d();
+                data();
+            }
+
+            //被拒绝了,只要有一个权限被拒绝那么就会调用
+            @Override
+            public void onPermissionsDenied() {
+                //拒绝了,如何处理?(视情况而定)
+                JLog.d();
+                permissionsHelper.setParams(null);
+            }
+
+            //用户已经永久的拒绝了
+            public void hasLockForever() {
+                JLog.i("hasLockForever");
+                permissionsHelper.setParams(null);
+            }
+
+            //被拒绝后,在最后一次申请权限之前
+            public void onBeforeRequestFinalPermissions(PermissionsHelper helper) {
+                JLog.i();
+                helper.continueRequestPermissions();
+            }
+        });
+    }
+
+    private void data() {
+        String url = "https://www.yjw1020.club/index/img/Ta_01.jpg";
+        JLog.v(url);
+        OkHttpUtil.getInstance(this).downloadFile(url).sync(null, new onOkHttpListener<String, String>() {
+
             public void onCompleted() {
+
             }
 
             public void onSuccess(String s) {
@@ -38,5 +89,32 @@ public class MainActivity extends AppCompatActivity {
                 JLog.v(s);
             }
         });
+//        String url = "https://www.yjw1020.club/api/myIndex.php";
+//        Map<Object, Object> oMap = new HashMap<>();
+//        oMap.put("type", "1");
+//        OkHttpUtil.getInstance(this).post(url).async(oMap, new onOkHttpListener<String, String>() {
+//            public void onCompleted() {
+//            }
+//
+//            public void onSuccess(String s) {
+//                JLog.v(s);
+//            }
+//
+//            public void onFailure(String s) {
+//                JLog.v(s);
+//            }
+//        });
+    }
+    @Override
+    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
+                                           @NonNull int[] grantResults) {
+        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
+        permissionsHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        permissionsHelper.onActivityResult(requestCode, resultCode, data);
     }
 }

+ 29 - 0
okhttp2/src/main/java/com/mylove/okhttp/DownloadBean.java

@@ -0,0 +1,29 @@
+package com.mylove.okhttp;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 14:02
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+class DownloadBean {
+    private String str;
+    private int progress;
+
+    public String getStr() {
+        return str;
+    }
+
+    public void setStr(String str) {
+        this.str = str;
+    }
+
+    public int getProgress() {
+        return progress;
+    }
+
+    public void setProgress(int progress) {
+        this.progress = progress;
+    }
+}

+ 180 - 0
okhttp2/src/main/java/com/mylove/okhttp/DownloadCall.java

@@ -0,0 +1,180 @@
+package com.mylove.okhttp;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.support.annotation.NonNull;
+
+import com.mylove.loglib.JLog;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.concurrent.TimeUnit;
+
+import okhttp3.Cache;
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import rx.Subscriber;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 13:46
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+class DownloadCall {
+    @SuppressLint("StaticFieldLeak")
+    private static Context mContext;
+    private String url;
+    private Subscriber<? super String> subscriber;
+    private Call call;
+    @SuppressLint("StaticFieldLeak")
+    private static DownloadCall instance;
+    private CallType callType;
+    private static OkHttpClient okHttpClient;
+
+    private DownloadCall(String url, Request request, Subscriber<? super String> subscriber, CallType callType) {
+        this.url = url;
+        this.subscriber = subscriber;
+        this.call = okHttpClient.newCall(request);
+        this.callType = callType;
+    }
+
+    /**
+     * okHttpClient初始化,并添加拦截及缓存
+     *
+     * @param context    上下文
+     * @param mCacheUrl  缓存地址
+     * @param request    请求
+     * @param subscriber 返回
+     * @param callType   请求类型
+     * @return
+     */
+    static DownloadCall getInstance(Context context, String mCacheUrl, Request request, Subscriber<? super String> subscriber, CallType callType) {
+        if (instance == null) {
+            synchronized (DownloadCall.class) {
+                if (instance == null) {
+                    mContext = context;
+                    OkHttpClient httpClient = new OkHttpClient();
+                    okHttpClient = httpClient.newBuilder()
+                            .addNetworkInterceptor(new CacheInterceptor())
+                            .cache(privateCache())
+                            .connectTimeout(30, TimeUnit.SECONDS)
+                            .readTimeout(30, TimeUnit.SECONDS)
+                            .build();
+                    instance = new DownloadCall(mCacheUrl, request, subscriber, callType);
+                }
+            }
+        }
+        return instance;
+    }
+
+    /**
+     * 请求
+     */
+    void sendCall() {
+        JLog.v();
+        if (callType == CallType.SYNC) {
+            sync();
+        } else if (callType == CallType.ASYNC) {
+            async();
+        }
+    }
+
+    /**
+     * 异步请求
+     */
+    private void sync() {
+        try {
+            Response execute = call.execute();
+            if (execute.isSuccessful()) {
+                JLog.v();
+                save(execute.body());
+            } else {
+                JLog.v();
+                subscriber.onCompleted();
+                subscriber.onError(new Error("请求失败"));
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+            JLog.v(e.getMessage());
+            subscriber.onCompleted();
+            subscriber.onError(new Error(e.getMessage()));
+        }
+    }
+
+    /**
+     * 同步请求
+     */
+    private void async() {
+        call.enqueue(new Callback() {
+            public void onFailure(@NonNull Call call, @NonNull IOException e) {
+                subscriber.onCompleted();
+                subscriber.onError(new Error(e.getMessage()));
+            }
+
+            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
+                save(response.body());
+            }
+        });
+    }
+
+    /**
+     * 保存
+     *
+     * @param body
+     */
+    private void save(ResponseBody body) {
+        int lastIndexOf = url.lastIndexOf("/");
+        String pathStr = url.subSequence(lastIndexOf + 1, url.length()).toString();
+        InputStream is = null;
+        FileOutputStream fos = null;
+        String path = FileUtil.getSDPath() + "/" + mContext.getPackageName() + "/" + pathStr;
+        File file = new File(path);
+        try {
+//            FileUtil.saveImage(bitmap, path);
+            byte[] buf = new byte[2048];
+            int len;
+//            long total = body.contentLength();
+//            long current = 0;
+            is = body.byteStream();
+            fos = new FileOutputStream(file);
+            while ((len = is.read(buf)) != -1) {
+//                current += len;
+                fos.write(buf, 0, len);
+            }
+            fos.flush();
+            subscriber.onNext(path);
+        } catch (Exception e) {
+            e.printStackTrace();
+            subscriber.onError(new Error(e.getMessage()));
+        }finally {
+            try {
+            if (is!=null){
+                is.close();
+            }
+            if (fos!=null){
+                fos.close();
+            }
+            }catch (Exception e){
+                e.printStackTrace();
+                subscriber.onError(new Error(e.getMessage()));
+            }
+        }
+        subscriber.onCompleted();
+    }
+
+    /**
+     * 设置缓存路径,以及缓存文件大小
+     */
+    private static Cache privateCache() {
+        return new Cache(mContext.getCacheDir(), 1024 * 1024);
+    }
+
+}

+ 142 - 0
okhttp2/src/main/java/com/mylove/okhttp/DownloadObservable.java

@@ -0,0 +1,142 @@
+package com.mylove.okhttp;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+
+import java.util.Map;
+
+import okhttp3.FormBody;
+import okhttp3.Request;
+import rx.Observable;
+import rx.Subscriber;
+import rx.android.schedulers.AndroidSchedulers;
+import rx.schedulers.Schedulers;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 13:38
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+class DownloadObservable {
+    @SuppressLint("StaticFieldLeak")
+    private static DownloadObservable instance;
+    @SuppressLint("StaticFieldLeak")
+    private static Context mContext;
+    private static RequestType requestType;
+    private static CallType callType;
+
+    static DownloadObservable getInstance(Context context, RequestType type1, CallType type2) {
+        if (instance == null) {
+            synchronized (DownloadObservable.class) {
+                if (instance == null) {
+                    instance = new DownloadObservable();
+                    mContext = context;
+                    requestType = type1;
+                    callType = type2;
+                }
+            }
+        }
+        return instance;
+    }
+
+    void request(String url, Map<Object, Object> oMap, final onOkHttpListener<String, String> onOkHttpListener) {
+        getObservable(url, oMap).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
+                .subscribe(new Subscriber<String>() {
+                    public void onCompleted() {
+                        onOkHttpListener.onCompleted();
+                    }
+
+                    public void onError(Throwable e) {
+                        onOkHttpListener.onFailure(e.getMessage());
+                    }
+
+                    public void onNext(String s) {
+                        onOkHttpListener.onSuccess(s);
+                    }
+                });
+    }
+
+    private Observable<String> getObservable(final String url, final Map<Object, Object> oMap) {
+        return Observable.create(new Observable.OnSubscribe<String>() {
+            public void call(Subscriber<? super String> subscriber) {
+                send(url, oMap, subscriber);
+            }
+        });
+    }
+
+    private void send(final String url, final Map<Object, Object> oMap, final Subscriber<? super String> subscriber) {
+        if (Internet.ifInternet(mContext)) {
+            Request request = getRequest(url, oMap);
+            DownloadCall.getInstance(mContext, url, request, subscriber, callType).sendCall();
+        } else {
+            subscriber.onCompleted();
+            subscriber.onError(new Exception("网络错误"));
+        }
+    }
+
+    /**
+     * 判断请求方式
+     *
+     * @param url  地址
+     * @param oMap 键值
+     * @return request
+     */
+    private Request getRequest(String url, Map<Object, Object> oMap) {
+        if (requestType == null) {
+            requestType = RequestType.GET;
+        }
+        switch (requestType) {
+            case GET:
+                return get(url, oMap);
+            case POST:
+                return post(url, oMap);
+            default:
+                return get(url, oMap);
+        }
+    }
+
+    /**
+     * get上传参数
+     *
+     * @param url  地址
+     * @param oMap 键值
+     * @return request
+     */
+    private Request get(String url, Map<Object, Object> oMap) {
+        StringBuilder str = new StringBuilder(url);
+        if (FormatUtil.isMapNotEmpty(oMap)) {
+            str.append("?");
+            for (Map.Entry<Object, Object> entry : oMap.entrySet()) {
+                str.append(entry.getKey()).append("=").append(entry).append("&");
+            }
+            str = new StringBuilder(str.substring(0, str.length() - 1));
+        }
+        return new Request.Builder()
+                .url(str.toString())
+                .get()
+                .build();
+    }
+
+    /**
+     * post上传参数
+     *
+     * @param url  地址
+     * @param oMap 键值
+     * @return request
+     */
+    private Request post(String url, Map<Object, Object> oMap) {
+        FormBody.Builder builder = new FormBody.Builder();
+        if (FormatUtil.isMapNotEmpty(oMap)) {
+            for (Map.Entry<Object, Object> entry : oMap.entrySet()) {
+                builder.add(entry.getKey().toString(), entry.getValue().toString());
+            }
+        }
+        FormBody build = builder.build();
+        return new Request.Builder()
+                .url(url)
+                .post(build)
+                .build();
+    }
+}

+ 44 - 0
okhttp2/src/main/java/com/mylove/okhttp/DownloadRequest.java

@@ -0,0 +1,44 @@
+package com.mylove.okhttp;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+
+import java.util.Map;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 13:36
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+public class DownloadRequest {
+    @SuppressLint("StaticFieldLeak")
+    private static DownloadRequest instance;
+    private static String url;
+    @SuppressLint("StaticFieldLeak")
+    private static Context mContext;
+    private static RequestType requestType;
+
+    public static DownloadRequest getInstance(Context context, String str, RequestType type) {
+        if (instance == null) {
+            synchronized (DownloadRequest.class) {
+                if (instance == null) {
+                    instance = new DownloadRequest();
+                    mContext = context;
+                    url = str;
+                    requestType = type;
+                }
+            }
+        }
+        return instance;
+    }
+
+    public void sync(Map<Object, Object> oMap, onOkHttpListener<String, String> onOkHttpListener) {
+        DownloadObservable.getInstance(mContext, requestType, CallType.SYNC).request(url, oMap, onOkHttpListener);
+    }
+
+    public void async(Map<Object, Object> oMap, onOkHttpListener<String, String> onOkHttpListener) {
+        DownloadObservable.getInstance(mContext, requestType, CallType.ASYNC).request(url, oMap, onOkHttpListener);
+    }
+}

+ 68 - 0
okhttp2/src/main/java/com/mylove/okhttp/FileUtil.java

@@ -0,0 +1,68 @@
+package com.mylove.okhttp;
+
+import android.graphics.Bitmap;
+import android.os.Environment;
+
+import com.mylove.loglib.JLog;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 13:55
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+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());
+            JLog.v(substring);
+            if (substring.equals("png")) {
+                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()
+                .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
+        if (sdCardExist) {//判断sd卡是否存在
+            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
+        }
+        return sdDir.toString();
+    }
+}

+ 37 - 37
okhttp2/src/main/java/com/mylove/okhttp/FormatUtil.java

@@ -19,10 +19,10 @@ import java.util.regex.Pattern;
 /**
  * 字符串工具类
  */
-public class FormatUtil {
+ class FormatUtil {
 
 
-    public static final String EMPTY = "";
+     static final String EMPTY = "";
 
     /**
      * 判断字符串是否为空
@@ -30,7 +30,7 @@ public class FormatUtil {
      * @param str
      * @return true 不为空, false 为空
      */
-    public static boolean isNotEmpty(String str) {
+     static boolean isNotEmpty(String str) {
         return str != null && !"null".equals(str) && str.trim().length() != 0;
     }
 
@@ -40,55 +40,55 @@ public class FormatUtil {
      * @param str
      * @return true 为空,false 不为空
      */
-    public static boolean isEmpty(String str) {
+     static boolean isEmpty(String str) {
         return str == null || "null".equals(str) || str.trim().length() == 0;
     }
 
-    public static final SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm", Locale.CHINA);
+     static final SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm", Locale.CHINA);
 
-    public static String getCurrentTime() {
+     static String getCurrentTime() {
         return dateformat.format(new Date());
     }
 
-    public static final SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
+     static final SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
 
-    public static String formatDateTime(long millseconds) {
+     static String formatDateTime(long millseconds) {
         return sdformat.format(new Date(millseconds));
     }
 
-    public static String getCurrentDateTime() {
+     static String getCurrentDateTime() {
         return sdformat.format(new Date());
     }
 
     /**
      * 判断集合是否为空
      */
-    public static <T> boolean isCollectionsNotEmpty(Collection<T> collection) {
+     static <T> boolean isCollectionsNotEmpty(Collection<T> collection) {
         return collection != null && collection.size() > 0;
     }
 
     /**
      * 判断MAP是否为空
      */
-    public static <K, V> boolean isMapNotEmpty(Map<K, V> map) {
+     static <K, V> boolean isMapNotEmpty(Map<K, V> map) {
         return map != null && map.size() > 0;
     }
 
     /**
      * 判断List是否为空
      */
-    public static boolean isListEmpty(List<?> array) {
+     static boolean isListEmpty(List<?> array) {
         return array != null && array.size() == 0;
     }
 
     /**
      * 判断JSON数组是否为空
      */
-    public static boolean isJSONArrayEmpty(JSONArray array) {
+     static boolean isJSONArrayEmpty(JSONArray array) {
         return array == null || array.length() == 0;
     }
 
-    public static boolean isObjectNotNull(Object object) {
+     static boolean isObjectNotNull(Object object) {
         if (object != null && object.getClass().isArray()) {
             // 如果是数组类型
             throw new UnsupportedOperationException("isObjectNotNull not supported operation :" + object);
@@ -99,32 +99,32 @@ public class FormatUtil {
     /**
      * 判断JSON数据不空为
      */
-    public static boolean isJSONArrayNotEmpty(JSONArray array) {
+     static boolean isJSONArrayNotEmpty(JSONArray array) {
         return array != null && array.length() > 0;
     }
 
     /**
      * 判断JSON数组是否为空
      */
-    public static boolean isJSONObjectEmpty(JSONObject object) {
+     static boolean isJSONObjectEmpty(JSONObject object) {
         return object == null || object.length() == 0;
     }
 
     /**
      * 判断JSON数据不空为
      */
-    public static boolean isJSONObjectNotEmpty(JSONObject object) {
+     static boolean isJSONObjectNotEmpty(JSONObject object) {
         return object != null && object.length() > 0;
     }
 
-    public static boolean isIntArrayNotEmpty(int[] array) {
+     static boolean isIntArrayNotEmpty(int[] array) {
         return array != null && array.length > 0;
     }
 
     /**
      * 判断List数据不空为
      */
-    public static boolean isListNotEmpty(List<?> array) {
+     static boolean isListNotEmpty(List<?> array) {
         return array != null && array.size() > 0;
     }
 
@@ -134,7 +134,7 @@ public class FormatUtil {
      * @param array
      * @return
      */
-    public static boolean isLongArrayNotEmpty(long[] array) {
+     static boolean isLongArrayNotEmpty(long[] array) {
         return array != null && array.length > 0;
     }
 
@@ -144,7 +144,7 @@ public class FormatUtil {
      * @param array
      * @return
      */
-    public static boolean isFloatArrayNotEmpty(float[] array) {
+     static boolean isFloatArrayNotEmpty(float[] array) {
         return array != null && array.length > 0;
     }
 
@@ -154,7 +154,7 @@ public class FormatUtil {
      * @param array
      * @return
      */
-    public static boolean isDoubleArrayNotEmpty(double[] array) {
+     static boolean isDoubleArrayNotEmpty(double[] array) {
         return array != null && array.length > 0;
     }
 
@@ -164,25 +164,25 @@ public class FormatUtil {
      * @param cardNum
      * @return 返回是否包含
      */
-    public static boolean isJudge(String cardNum) {
+     static boolean isJudge(String cardNum) {
         String regex = ".*[a-zA-Z]+.*";
         Matcher m = Pattern.compile(regex).matcher(cardNum);
         return m.matches();
     }
 
-    public static boolean isNotBlank(String str) {
+     static boolean isNotBlank(String str) {
         return (str != null) && (str.length() != 0);
     }
 
-    public static boolean isBlank(String str) {
+     static boolean isBlank(String str) {
         return (str == null) || (str.length() == 0);
     }
 
-    public static boolean isNotTrimBlank(String str) {
+     static boolean isNotTrimBlank(String str) {
         return (str != null) && (str.trim().length() != 0);
     }
 
-    public static boolean isTrimBlank(String str) {
+     static boolean isTrimBlank(String str) {
         return (str == null) || (str.trim().length() == 0);
     }
 
@@ -192,7 +192,7 @@ public class FormatUtil {
      * @param idNo
      * @return
      */
-    public static boolean isIdNo(String idNo) {
+     static boolean isIdNo(String idNo) {
 //        if (isTrimBlank(idNo))
 //        {
 //            return false;
@@ -214,7 +214,7 @@ public class FormatUtil {
      * @param mobiles
      * @return
      */
-    public static boolean isNotMobileNO(String mobiles) {
+     static boolean isNotMobileNO(String mobiles) {
 //        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
         Pattern p = Pattern.compile("^((1[358][0-9])|(14[57])|(17[0678]))\\d{8}$");
         Matcher m = p.matcher(mobiles);
@@ -227,7 +227,7 @@ public class FormatUtil {
      * @param email
      * @return
      */
-    public static boolean isEmail(String email) {
+     static boolean isEmail(String email) {
         if (isTrimBlank(email)) {
             return false;
         }
@@ -243,7 +243,7 @@ public class FormatUtil {
      * @param source
      * @return
      */
-    public static String htmlEscapeCharsToString(String source) {
+     static String htmlEscapeCharsToString(String source) {
         return FormatUtil.isEmpty(source) ? source : source.replaceAll("&lt;", "<")
                 .replaceAll("&gt;", ">")
                 .replaceAll("&amp;", "&")
@@ -264,7 +264,7 @@ public class FormatUtil {
      * @param id
      * @return
      */
-    public static boolean isNotUserName(String id) {
+     static boolean isNotUserName(String id) {
         if (isTrimBlank(id)) {
             return false;
         }
@@ -274,7 +274,7 @@ public class FormatUtil {
         return !m.find();
     }
 
-    public static boolean isNotPassWord(String password) {
+     static boolean isNotPassWord(String password) {
         if (isTrimBlank(password)) {
             return false;
         }
@@ -290,7 +290,7 @@ public class FormatUtil {
      * @param bankCard
      * @return
      */
-    public static boolean isNotBank(String bankCard) {
+     static boolean isNotBank(String bankCard) {
         if (isTrimBlank(bankCard)) {
             return false;
         }
@@ -306,7 +306,7 @@ public class FormatUtil {
      * @param str
      * @return
      */
-    public static String isStringFormat(Context context, int resId, String str) {
+     static String isStringFormat(Context context, int resId, String str) {
         return String.format(context.getResources().getString(resId), str);
     }
 
@@ -317,7 +317,7 @@ public class FormatUtil {
      * @param resId
      * @return
      */
-    public static String getFromRaw(Context context, int resId) {
+     static String getFromRaw(Context context, int resId) {
         try {
             InputStreamReader inputReader = new InputStreamReader(context.getResources().openRawResource(resId));
             BufferedReader bufReader = new BufferedReader(inputReader);
@@ -333,7 +333,7 @@ public class FormatUtil {
     }
 
     // 直接从assets读取
-    public static String getFromAssets(Context context, String fileName) {
+     static String getFromAssets(Context context, String fileName) {
         try {
             InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
             BufferedReader bufReader = new BufferedReader(inputReader);

+ 2 - 2
okhttp2/src/main/java/com/mylove/okhttp/OkCall.java

@@ -113,7 +113,7 @@ class OkCall {
                 subscriber.onNext(json);
                 subscriber.onCompleted();
             } else {
-                subscriber.onError(new Exception(e));
+                subscriber.onError(new Exception(e.getMessage()));
             }
         }
     }
@@ -129,7 +129,7 @@ class OkCall {
                     subscriber.onNext(json);
                     subscriber.onCompleted();
                 } else {
-                    subscriber.onError(new Exception(e));
+                    subscriber.onError(new Exception(e.getMessage()));
                 }
             }
 

+ 4 - 0
okhttp2/src/main/java/com/mylove/okhttp/OkHttpUtil.java

@@ -44,4 +44,8 @@ public class OkHttpUtil {
     public AutoRequest postAll(String url) {
         return AutoRequest.getInstance(mContext, url, RequestType.UP_FILE);
     }
+
+    public DownloadRequest downloadFile(String url) {
+        return DownloadRequest.getInstance(mContext, url, RequestType.GET);
+    }
 }

+ 1 - 1
okhttp2/src/main/java/com/mylove/okhttp/RequestType.java

@@ -11,5 +11,5 @@ enum RequestType {
     GET,
     POST,
     UP_FILE,
-    ALL
+    ALL,
 }

+ 12 - 0
okhttp2/src/main/java/com/mylove/okhttp/onOkHttpDownload.java

@@ -0,0 +1,12 @@
+package com.mylove.okhttp;
+
+/**
+ * @author myLove
+ * @time 2017/11/24 13:57
+ * @e-mail mylove.520.y@gmail.com
+ * @overview
+ */
+
+public interface onOkHttpDownload<K, T> extends onOkHttpListener<K, T> {
+    void onDownloading(int progress);
+}