From 1c504a563180577a13959b5383dc163fee955fe5 Mon Sep 17 00:00:00 2001 From: chouxingxing <814852645@qq.com> Date: Mon, 28 Dec 2020 18:15:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=AF=B9=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E5=8F=8A=E7=BD=91=E7=BB=9C=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E7=9A=84=E5=B0=81=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/main/AndroidManifest.xml | 4 +- .../java/com/vector/commonlibrary/App.java | 34 ++ .../vector/commonlibrary/MainActivity.java | 38 ++ readme.md | 3 +- vector_common/build.gradle | 7 +- vector_common/src/main/AndroidManifest.xml | 5 + .../com/vector/common/app/ConfigType.java | 4 +- .../com/vector/common/app/Configurator.java | 50 ++- .../java/com/vector/common/app/Vector.java | 21 +- .../com/vector/common/net/HttpMethod.java | 18 + .../com/vector/common/net/RestClient.java | 169 ++++++++ .../vector/common/net/RestClientBuilder.java | 166 ++++++++ .../com/vector/common/net/RestCreator.java | 67 ++++ .../com/vector/common/net/RestService.java | 55 +++ .../vector/common/net/callback/IError.java | 11 + .../vector/common/net/callback/IFailure.java | 11 + .../vector/common/net/callback/IRequest.java | 13 + .../vector/common/net/callback/ISuccess.java | 11 + .../common/net/callback/RequestCallbacks.java | 80 ++++ .../common/net/download/DownloadHandler.java | 94 +++++ .../common/net/download/SaveFileTask.java | 76 ++++ .../common/ui/loader/LoaderCreator.java | 53 +++ .../common/ui/loader/LoaderManager.java | 70 ++++ .../vector/common/ui/loader/LoaderStyle.java | 38 ++ .../common/utils/display/DimenUtil.java | 30 ++ .../vector/common/utils/log/LoggerUtil.java | 79 ++++ .../vector/common/utils/storage/FileUtil.java | 367 ++++++++++++++++++ vector_common/src/main/res/values/ids.xml | 5 + vector_common/src/main/res/values/style.xml | 21 + 29 files changed, 1581 insertions(+), 19 deletions(-) create mode 100644 app/src/main/java/com/vector/commonlibrary/App.java create mode 100644 vector_common/src/main/java/com/vector/common/net/HttpMethod.java create mode 100644 vector_common/src/main/java/com/vector/common/net/RestClient.java create mode 100644 vector_common/src/main/java/com/vector/common/net/RestClientBuilder.java create mode 100644 vector_common/src/main/java/com/vector/common/net/RestCreator.java create mode 100644 vector_common/src/main/java/com/vector/common/net/RestService.java create mode 100644 vector_common/src/main/java/com/vector/common/net/callback/IError.java create mode 100644 vector_common/src/main/java/com/vector/common/net/callback/IFailure.java create mode 100644 vector_common/src/main/java/com/vector/common/net/callback/IRequest.java create mode 100644 vector_common/src/main/java/com/vector/common/net/callback/ISuccess.java create mode 100644 vector_common/src/main/java/com/vector/common/net/callback/RequestCallbacks.java create mode 100644 vector_common/src/main/java/com/vector/common/net/download/DownloadHandler.java create mode 100644 vector_common/src/main/java/com/vector/common/net/download/SaveFileTask.java create mode 100644 vector_common/src/main/java/com/vector/common/ui/loader/LoaderCreator.java create mode 100644 vector_common/src/main/java/com/vector/common/ui/loader/LoaderManager.java create mode 100644 vector_common/src/main/java/com/vector/common/ui/loader/LoaderStyle.java create mode 100644 vector_common/src/main/java/com/vector/common/utils/display/DimenUtil.java create mode 100644 vector_common/src/main/java/com/vector/common/utils/log/LoggerUtil.java create mode 100644 vector_common/src/main/java/com/vector/common/utils/storage/FileUtil.java create mode 100644 vector_common/src/main/res/values/ids.xml create mode 100644 vector_common/src/main/res/values/style.xml diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d01695f..9073787 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,12 +3,14 @@ package="com.vector.commonlibrary"> + android:theme="@style/Theme.Vector_CommonLibrary" + android:usesCleartextTraffic="true"> diff --git a/app/src/main/java/com/vector/commonlibrary/App.java b/app/src/main/java/com/vector/commonlibrary/App.java new file mode 100644 index 0000000..345b889 --- /dev/null +++ b/app/src/main/java/com/vector/commonlibrary/App.java @@ -0,0 +1,34 @@ +package com.vector.commonlibrary; + +import android.app.Application; + +import androidx.annotation.Nullable; + +import com.orhanobut.logger.AndroidLogAdapter; +import com.orhanobut.logger.DiskLogAdapter; +import com.orhanobut.logger.FormatStrategy; +import com.orhanobut.logger.Logger; +import com.orhanobut.logger.PrettyFormatStrategy; +import com.vector.common.app.Vector; +import com.vector.common.utils.log.LoggerUtil; + +/** + * @author Vector Weng + * @description: + * @date :2020/12/21 16:49 + */ +public class App extends Application { + + @Override + public void onCreate() { + super.onCreate(); + + Vector.init(this) + .withLoaderDelayed(2000) + .initLogger(LoggerUtil.LoggerLevel.VERBOSE) + .withApiHost("http://192.168.31.80:20002/api/") + .configure(); + } + + +} diff --git a/app/src/main/java/com/vector/commonlibrary/MainActivity.java b/app/src/main/java/com/vector/commonlibrary/MainActivity.java index 237cb2d..f2961bc 100644 --- a/app/src/main/java/com/vector/commonlibrary/MainActivity.java +++ b/app/src/main/java/com/vector/commonlibrary/MainActivity.java @@ -3,6 +3,17 @@ import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; +import android.util.Log; + +import com.vector.common.app.ConfigType; +import com.vector.common.app.Vector; +import com.vector.common.net.RestClient; +import com.vector.common.net.callback.IError; +import com.vector.common.net.callback.IFailure; +import com.vector.common.net.callback.ISuccess; +import com.vector.common.utils.log.LoggerUtil; + +import java.util.logging.Logger; public class MainActivity extends AppCompatActivity { @@ -10,5 +21,32 @@ public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); + + RestClient.bulider() + .loader(MainActivity.this) + .url("https://www.baidu.com") + .success(new ISuccess() { + @Override + public void onSuccess(String response) { + Log.i("MainActivity", response); + } + }) + .error(new IError() { + @Override + public void onError(int code, String msg) { + Log.i("MainActivity", code + ""); + + } + }) + .failure(new IFailure() { + @Override + public void onFailure() { + Log.i("MainActivity", "失败"); + + } + }) + .bulid() + .get(); + } } \ No newline at end of file diff --git a/readme.md b/readme.md index 951c4fe..71c180d 100644 --- a/readme.md +++ b/readme.md @@ -1 +1,2 @@ -#####https://www.cnblogs.com/zhangzhonghui/p/11463250.html \ No newline at end of file +### 单例模式之Holder +https://www.cnblogs.com/zhangzhonghui/p/11463250.html \ No newline at end of file diff --git a/vector_common/build.gradle b/vector_common/build.gradle index 9129b8e..e2e4321 100644 --- a/vector_common/build.gradle +++ b/vector_common/build.gradle @@ -17,6 +17,8 @@ android { } buildTypes { + + release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' @@ -34,7 +36,8 @@ dependencies { implementation 'com.google.android.material:material:1.2.1' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' - + //logger + api 'com.orhanobut:logger:2.2.0' //字体图标库 implementation 'com.joanzapata.iconify:android-iconify-fontawesome:2.2.2' implementation 'com.joanzapata.iconify:android-iconify-ionicons:2.2.2' @@ -43,4 +46,6 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-scalars:2.3.0' + //AVLoadingIndicatorView + implementation 'com.wang.avi:library:2.1.3' } \ No newline at end of file diff --git a/vector_common/src/main/AndroidManifest.xml b/vector_common/src/main/AndroidManifest.xml index 6b46ddb..def2d92 100644 --- a/vector_common/src/main/AndroidManifest.xml +++ b/vector_common/src/main/AndroidManifest.xml @@ -2,4 +2,9 @@ + + + + + \ No newline at end of file diff --git a/vector_common/src/main/java/com/vector/common/app/ConfigType.java b/vector_common/src/main/java/com/vector/common/app/ConfigType.java index 3af08e7..85d9646 100644 --- a/vector_common/src/main/java/com/vector/common/app/ConfigType.java +++ b/vector_common/src/main/java/com/vector/common/app/ConfigType.java @@ -10,5 +10,7 @@ public enum ConfigType { CONFIG_READY, ICON, LOADER_DELAYED, - INTERCEPTOR + INTERCEPTOR, + HANDLER, + LOGGER_LEVEL } diff --git a/vector_common/src/main/java/com/vector/common/app/Configurator.java b/vector_common/src/main/java/com/vector/common/app/Configurator.java index ae15be4..5119e63 100644 --- a/vector_common/src/main/java/com/vector/common/app/Configurator.java +++ b/vector_common/src/main/java/com/vector/common/app/Configurator.java @@ -1,9 +1,13 @@ package com.vector.common.app; import android.content.Context; +import android.os.Handler; import com.joanzapata.iconify.IconFontDescriptor; import com.joanzapata.iconify.Iconify; +import com.orhanobut.logger.AndroidLogAdapter; +import com.orhanobut.logger.FormatStrategy; +import com.orhanobut.logger.Logger; import java.util.ArrayList; import java.util.HashMap; @@ -17,12 +21,16 @@ */ public class Configurator { - private static final HashMap VECTOR_CONFIGS = new HashMap<>(); + private static final HashMap VECTOR_CONFIGS = new HashMap<>(); + private static final Handler HANDLER = new Handler(); + private static final ArrayList ICONS = new ArrayList<>(); private static final ArrayList INTERCEPTORS = new ArrayList<>(); private Configurator() { - VECTOR_CONFIGS.put(ConfigType.CONFIG_READY.name(), false); + VECTOR_CONFIGS.put(ConfigType.CONFIG_READY, false); + VECTOR_CONFIGS.put(ConfigType.HANDLER, HANDLER); + } private static final class Holder { @@ -35,20 +43,40 @@ public static Configurator getInstance() { public final void configure() { initIcons(); - VECTOR_CONFIGS.put(ConfigType.CONFIG_READY.name(), true); + VECTOR_CONFIGS.put(ConfigType.CONFIG_READY, true); } - final HashMap getConfigs() { + final HashMap getConfigs() { return VECTOR_CONFIGS; } + public final Configurator initLogger(int level) { + initLogger(level, null); + return this; + } + + public final Configurator initLogger(int level, FormatStrategy formatStrategy) { + if (formatStrategy != null) { + Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); + } else { + Logger.addLogAdapter(new AndroidLogAdapter()); + } + VECTOR_CONFIGS.put(ConfigType.LOGGER_LEVEL, level); + return this; + } + public final Configurator withContext(Context context) { - VECTOR_CONFIGS.put(ConfigType.APPLICATION_CONTEXT.name(), context); + VECTOR_CONFIGS.put(ConfigType.APPLICATION_CONTEXT, context); return this; } public final Configurator withApiHost(String host) { - VECTOR_CONFIGS.put(ConfigType.API_HOST.name(), host); + VECTOR_CONFIGS.put(ConfigType.API_HOST, host); + return this; + } + + public final Configurator withLoaderDelayed(long delayed) { + VECTOR_CONFIGS.put(ConfigType.LOADER_DELAYED, delayed); return this; } @@ -59,13 +87,13 @@ public final Configurator withIcon(IconFontDescriptor descriptor) { public final Configurator withInterceptor(Interceptor interceptor) { INTERCEPTORS.add(interceptor); - VECTOR_CONFIGS.put(ConfigType.INTERCEPTOR.name(), INTERCEPTORS); + VECTOR_CONFIGS.put(ConfigType.INTERCEPTOR, INTERCEPTORS); return this; } public final Configurator withInterceptor(ArrayList interceptors) { INTERCEPTORS.addAll(interceptors); - VECTOR_CONFIGS.put(ConfigType.INTERCEPTOR.name(), INTERCEPTORS); + VECTOR_CONFIGS.put(ConfigType.INTERCEPTOR, INTERCEPTORS); return this; } @@ -79,14 +107,14 @@ private void initIcons() { } private void checkConfiguration() { - final boolean isReady = (boolean) VECTOR_CONFIGS.get(ConfigType.CONFIG_READY.name()); + final boolean isReady = (boolean) VECTOR_CONFIGS.get(ConfigType.CONFIG_READY); if (!isReady) throw new RuntimeException("Configuration is not ready,call configure"); } - final T getConfiguration(Enum key) { + final T getConfiguration(ConfigType key) { checkConfiguration(); - return (T) VECTOR_CONFIGS.get(key.name()); + return (T) VECTOR_CONFIGS.get(key); } diff --git a/vector_common/src/main/java/com/vector/common/app/Vector.java b/vector_common/src/main/java/com/vector/common/app/Vector.java index dbc8ddb..de155ca 100644 --- a/vector_common/src/main/java/com/vector/common/app/Vector.java +++ b/vector_common/src/main/java/com/vector/common/app/Vector.java @@ -1,6 +1,8 @@ package com.vector.common.app; +import android.app.Application; import android.content.Context; +import android.os.Handler; import java.util.HashMap; @@ -12,16 +14,27 @@ public class Vector { public static final Configurator init(Context context) { + getConfigurator() + .getConfigs() + .put(ConfigType.APPLICATION_CONTEXT, context.getApplicationContext()); return Configurator.getInstance(); } - public static HashMap getConfigs() { - return Configurator.getInstance().getConfigs(); + public static Configurator getConfigurator() { + return Configurator.getInstance(); } - public static Context getApplicationContext() { - return (Context) getConfigs().get(ConfigType.APPLICATION_CONTEXT); + public static T getConfiguration(ConfigType key) { + return getConfigurator().getConfiguration(key); + } + public static Application getApplicationContext() { + return getConfiguration(ConfigType.APPLICATION_CONTEXT); } + public static Handler getHandler() { + return getConfiguration(ConfigType.HANDLER); + } + + } diff --git a/vector_common/src/main/java/com/vector/common/net/HttpMethod.java b/vector_common/src/main/java/com/vector/common/net/HttpMethod.java new file mode 100644 index 0000000..45e0e03 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/HttpMethod.java @@ -0,0 +1,18 @@ +package com.vector.common.net; + +/** + * @author Vector Weng + * @description: + * @date :2020/12/9 18:44 + */ +public enum HttpMethod { + + GET, + POST, + POST_RAW, + PUT, + PUT_RAW, + DELETE, + UPLOAD + +} diff --git a/vector_common/src/main/java/com/vector/common/net/RestClient.java b/vector_common/src/main/java/com/vector/common/net/RestClient.java new file mode 100644 index 0000000..12d4ada --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/RestClient.java @@ -0,0 +1,169 @@ +package com.vector.common.net; + +import android.content.Context; + +import com.vector.common.net.callback.IError; +import com.vector.common.net.callback.IFailure; +import com.vector.common.net.callback.IRequest; +import com.vector.common.net.callback.ISuccess; +import com.vector.common.net.callback.RequestCallbacks; +import com.vector.common.net.download.DownloadHandler; +import com.vector.common.ui.loader.LoaderManager; +import com.vector.common.ui.loader.LoaderStyle; + +import java.io.File; +import java.util.Map; + +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.RequestBody; +import retrofit2.Call; + +/** + * @author Vector Weng + * @description: + * @date :2020/12/9 18:46 + */ +public class RestClient { + + private final String URL; + private final Map PARAMS; + private final IRequest REQUEST; + private final String DOWNLOAD_DIR; + private final String EXTENSION; + private final String NAME; + private final IError ERROR; + private final ISuccess SUCCESS; + private final IFailure FAILURE; + private final RequestBody BOBY; + private final LoaderStyle LOADER_STYLE; + private final File FILE; + private final Context CONTEXT; + + RestClient(String URL, + Map PARAMS, + String DOWNLOAD_DIR, + String EXTENSION, + String NAME, + IRequest REQUEST, + IError ERROR, + ISuccess SUCCESS, + IFailure FAILURE, + RequestBody BOBY, + LoaderStyle LOADERSTYLE, + File FILE, + Context CONTEXT) { + this.URL = URL; + this.PARAMS = PARAMS; + this.DOWNLOAD_DIR = DOWNLOAD_DIR; + this.EXTENSION = EXTENSION; + this.NAME = NAME; + this.REQUEST = REQUEST; + this.ERROR = ERROR; + this.SUCCESS = SUCCESS; + this.FAILURE = FAILURE; + this.BOBY = BOBY; + this.LOADER_STYLE = LOADERSTYLE; + this.FILE = FILE; + this.CONTEXT = CONTEXT; + } + + public static RestClientBuilder bulider() { + return new RestClientBuilder(); + } + + private void request(HttpMethod method) { + + final RestService service = RestCreator.getRestService(); + Call call = null; + + if (REQUEST != null) { + REQUEST.onRequestStart(); + } + + if (LOADER_STYLE != null) { + LoaderManager.showLoading(CONTEXT, LOADER_STYLE); + } + + switch (method) { + case GET: + call = service.get(URL, PARAMS); + break; + case PUT: + call = service.put(URL, PARAMS); + break; + case POST: + call = service.post(URL, PARAMS); + break; + case POST_RAW: + call = service.postRaw(URL, BOBY); + break; + case PUT_RAW: + call = service.putRaw(URL, BOBY); + case DELETE: + call = service.delete(URL, PARAMS); + break; + case UPLOAD: + final RequestBody requestBody = + RequestBody.create(MediaType.parse(MultipartBody.FORM.toString()), FILE); + final MultipartBody.Part body = MultipartBody.Part.createFormData("file", FILE.getName(), requestBody); + call = service.upload(URL, body); + break; + default: + break; + } + + if (call != null) { + call.enqueue(getRequestCallback()); + } + + } + + private RequestCallbacks getRequestCallback() { + return new RequestCallbacks(REQUEST, SUCCESS, FAILURE, ERROR, LOADER_STYLE); + } + + public final void get() { + request(HttpMethod.GET); + } + + public final void put() { + + if (BOBY == null) { + request(HttpMethod.PUT); + } else { + if (!PARAMS.isEmpty()) { + throw new RuntimeException("params must be null"); + } + request(HttpMethod.PUT_RAW); + } + + } + + public final void post() { + + if (BOBY == null) { + request(HttpMethod.POST); + } else { + if (!PARAMS.isEmpty()) { + throw new RuntimeException("params must be null"); + } + request(HttpMethod.POST_RAW); + } + + } + + public final void delete() { + request(HttpMethod.DELETE); + } + + public final void upload() { + request(HttpMethod.UPLOAD); + } + + public final void download() { + new DownloadHandler(URL, PARAMS, REQUEST, DOWNLOAD_DIR, EXTENSION, NAME, ERROR, SUCCESS, FAILURE).handlerDownload(); + } + + +} diff --git a/vector_common/src/main/java/com/vector/common/net/RestClientBuilder.java b/vector_common/src/main/java/com/vector/common/net/RestClientBuilder.java new file mode 100644 index 0000000..1d1916f --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/RestClientBuilder.java @@ -0,0 +1,166 @@ +package com.vector.common.net; + +import android.content.Context; + + +import com.vector.common.net.callback.IError; +import com.vector.common.net.callback.IFailure; +import com.vector.common.net.callback.IRequest; +import com.vector.common.net.callback.ISuccess; +import com.vector.common.ui.loader.LoaderStyle; + +import java.io.File; +import java.util.Map; +import java.util.WeakHashMap; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public class RestClientBuilder { + + private String mUrl = null; + private static final Map PARAMS = RestCreator.getParams(); + private IRequest mRequest = null; + private IError mError = null; + private ISuccess mSuccess = null; + private IFailure mFailure = null; + private RequestBody mBoby = null; + private Context mContext = null; + private LoaderStyle mLoaderStyle = null; + private File mFile = null; + private String mName = null; + private String mDownload_dir = null; + private String mExtension = null; + + RestClientBuilder() { + } + + public final RestClientBuilder url(String url) { + + this.mUrl = url; + return this; + + } + + public final RestClientBuilder params(WeakHashMap params) { + + PARAMS.putAll(params); + return this; + + } + + public final RestClientBuilder params(String key, Object value) { + + + PARAMS.put(key, value); + return this; + + } + + public final RestClientBuilder file(File file) { + + this.mFile = file; + return this; + + } + + public final RestClientBuilder file(String path) { + + this.mFile = new File(path); + return this; + + } + + public final RestClientBuilder name(String name) { + + this.mName = name; + return this; + + } + + public final RestClientBuilder dir(String dir) { + + this.mDownload_dir = dir; + return this; + + } + + public final RestClientBuilder extension(String extension) { + + this.mExtension = extension; + return this; + + } + + public final RestClientBuilder raw(String raw) { + + this.mBoby = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), raw); + return this; + + } + + public final RestClientBuilder onRequest(IRequest iRequest) { + + this.mRequest = iRequest; + return this; + + } + + public final RestClientBuilder success(ISuccess iSuccess) { + + this.mSuccess = iSuccess; + return this; + + } + + public final RestClientBuilder failure(IFailure iFailure) { + + this.mFailure = iFailure; + return this; + + } + + public final RestClientBuilder error(IError iError) { + + this.mError = iError; + return this; + + } + + public final RestClientBuilder loader(Context context, LoaderStyle loaderStyle) { + this.mContext = context; + this.mLoaderStyle = loaderStyle; + return this; + } + + public final RestClientBuilder loader(Context context) { + this.mContext = context; + this.mLoaderStyle = LoaderStyle.BallSpinFadeLoaderIndicator; + return this; + } + + public final RestClient bulid() { + return new RestClient( + mUrl, + PARAMS, + mDownload_dir, + mExtension, + mName, + mRequest, + mError, + mSuccess, + mFailure, + mBoby, + mLoaderStyle, + mFile, + mContext); + + } + +} + + diff --git a/vector_common/src/main/java/com/vector/common/net/RestCreator.java b/vector_common/src/main/java/com/vector/common/net/RestCreator.java new file mode 100644 index 0000000..3cd9f08 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/RestCreator.java @@ -0,0 +1,67 @@ +package com.vector.common.net; + + +import com.vector.common.app.ConfigType; +import com.vector.common.app.Vector; + +import java.util.ArrayList; +import java.util.WeakHashMap; +import java.util.concurrent.TimeUnit; + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public class RestCreator { + + private static final class ParamsHolder { + public static final WeakHashMap PARAMS = new WeakHashMap<>(); + } + + public static WeakHashMap getParams() { + return ParamsHolder.PARAMS; + } + + private static final class RetrofitHolder { + private static final String BASE_URL = (String) Vector.getConfiguration(ConfigType.API_HOST); + private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder() + .baseUrl(BASE_URL) + .client(OKHttpHolder.OK_HTTP_CLIENT) + .addConverterFactory(ScalarsConverterFactory.create()) + .build(); + } + + private static final class OKHttpHolder { + private static final int TIME_OUT = 60; + private static final ArrayList INTERCEPTORS = (ArrayList) Vector.getConfiguration(ConfigType.INTERCEPTOR); + private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder(); + + private static final OkHttpClient.Builder addInterceptor() { + if (INTERCEPTORS != null && !INTERCEPTORS.isEmpty()) { + for (Interceptor interceptor : INTERCEPTORS) { + BUILDER.addInterceptor(interceptor); + } + } + return BUILDER; + } + + private static final OkHttpClient OK_HTTP_CLIENT = + addInterceptor(). + connectTimeout(TIME_OUT, TimeUnit.SECONDS). + build(); + } + + private static final class RestServiceHolder { + private static final RestService REST_SERVICE = RetrofitHolder.RETROFIT_CLIENT.create(RestService.class); + } + + public static RestService getRestService() { + return RestServiceHolder.REST_SERVICE; + } + +} diff --git a/vector_common/src/main/java/com/vector/common/net/RestService.java b/vector_common/src/main/java/com/vector/common/net/RestService.java new file mode 100644 index 0000000..b361df3 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/RestService.java @@ -0,0 +1,55 @@ +package com.vector.common.net; + +import java.util.Map; + +import okhttp3.MultipartBody; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.http.Body; +import retrofit2.http.DELETE; +import retrofit2.http.FieldMap; +import retrofit2.http.FormUrlEncoded; +import retrofit2.http.GET; +import retrofit2.http.Multipart; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Part; +import retrofit2.http.QueryMap; +import retrofit2.http.Streaming; +import retrofit2.http.Url; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public interface RestService { + + @GET + Call get(@Url String url, @QueryMap Map params); + + @FormUrlEncoded + @POST + Call post(@Url String url, @FieldMap Map params); + + @POST + Call postRaw(@Url String url, @Body RequestBody body); + + @FormUrlEncoded + @PUT + Call put(@Url String url, @FieldMap Map params); + + @PUT + Call putRaw(@Url String url, @Body RequestBody body); + + @DELETE + Call delete(@Url String url, @QueryMap Map params); + + @Streaming + @GET + Call download(@Url String url, @QueryMap Map params); + + @Multipart + @POST + Call upload(@Url String url, @Part MultipartBody.Part file); +} diff --git a/vector_common/src/main/java/com/vector/common/net/callback/IError.java b/vector_common/src/main/java/com/vector/common/net/callback/IError.java new file mode 100644 index 0000000..0d34ffe --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/callback/IError.java @@ -0,0 +1,11 @@ +package com.vector.common.net.callback; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public interface IError { + + void onError(int code, String msg); + +} diff --git a/vector_common/src/main/java/com/vector/common/net/callback/IFailure.java b/vector_common/src/main/java/com/vector/common/net/callback/IFailure.java new file mode 100644 index 0000000..9507591 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/callback/IFailure.java @@ -0,0 +1,11 @@ +package com.vector.common.net.callback; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public interface IFailure { + + void onFailure(); + +} diff --git a/vector_common/src/main/java/com/vector/common/net/callback/IRequest.java b/vector_common/src/main/java/com/vector/common/net/callback/IRequest.java new file mode 100644 index 0000000..4c80816 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/callback/IRequest.java @@ -0,0 +1,13 @@ +package com.vector.common.net.callback; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public interface IRequest { + + void onRequestStart(); + + void onRequestEnd(); + +} diff --git a/vector_common/src/main/java/com/vector/common/net/callback/ISuccess.java b/vector_common/src/main/java/com/vector/common/net/callback/ISuccess.java new file mode 100644 index 0000000..934611e --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/callback/ISuccess.java @@ -0,0 +1,11 @@ +package com.vector.common.net.callback; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public interface ISuccess { + + void onSuccess(String response); + +} diff --git a/vector_common/src/main/java/com/vector/common/net/callback/RequestCallbacks.java b/vector_common/src/main/java/com/vector/common/net/callback/RequestCallbacks.java new file mode 100644 index 0000000..8d817d5 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/callback/RequestCallbacks.java @@ -0,0 +1,80 @@ +package com.vector.common.net.callback; + +import android.os.Handler; +import android.util.Log; + + +import com.vector.common.app.ConfigType; +import com.vector.common.app.Vector; +import com.vector.common.ui.loader.LoaderManager; +import com.vector.common.ui.loader.LoaderStyle; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +/** + * Created by 瓮少波 on 2018/4/24. + */ + +public class RequestCallbacks implements Callback { + + private final IRequest REQUEST; + private final ISuccess SUCCESS; + private final IFailure FAILURE; + private final IError ERROR; + private final LoaderStyle LOADER_STYLE; + private static final Handler HANDLER = Vector.getHandler(); + + + public RequestCallbacks(IRequest request, ISuccess success, IFailure failure, IError error, LoaderStyle loaderStyle) { + this.REQUEST = request; + this.SUCCESS = success; + this.FAILURE = failure; + this.ERROR = error; + this.LOADER_STYLE = loaderStyle; + } + + @Override + public void onResponse(Call call, Response response) { + + if (response.isSuccessful()) { + if (call.isExecuted()) { + if (SUCCESS != null) { + SUCCESS.onSuccess(response.body()); + } + } + } else { + if (ERROR != null) { + ERROR.onError(response.code(), response.message()); + } + } + onRequestFinish(); + + } + + @Override + public void onFailure(Call call, Throwable t) { + if (FAILURE != null) { + FAILURE.onFailure(); + Log.i("Main", t.toString()); + } + if (REQUEST != null) { + REQUEST.onRequestEnd(); + } + onRequestFinish(); + + } + + private void onRequestFinish() { + final long delayed = Vector.getConfiguration(ConfigType.LOADER_DELAYED); + if (LOADER_STYLE != null) { + HANDLER.postDelayed(new Runnable() { + @Override + public void run() { + LoaderManager.stopLoading(); + } + }, delayed); + } + } +} diff --git a/vector_common/src/main/java/com/vector/common/net/download/DownloadHandler.java b/vector_common/src/main/java/com/vector/common/net/download/DownloadHandler.java new file mode 100644 index 0000000..037efdb --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/download/DownloadHandler.java @@ -0,0 +1,94 @@ +package com.vector.common.net.download; + +import android.os.AsyncTask; + +import com.vector.common.net.RestCreator; +import com.vector.common.net.callback.IError; +import com.vector.common.net.callback.IFailure; +import com.vector.common.net.callback.IRequest; +import com.vector.common.net.callback.ISuccess; + +import java.util.Map; + +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +public class DownloadHandler { + + + private final String URL; + private final Map PARAMS; + private final IRequest REQUEST; + private final String DOWNLOAD_DIR; + private final String EXTENSION; + private final String NAME; + private final IError ERROR; + private final ISuccess SUCCESS; + private final IFailure FAILURE; + + public DownloadHandler(String URL, + Map PARAMS, + IRequest REQUEST, + String DOWNLOAD_DIR, + String EXTENSION, + String NAME, + IError ERROR, + ISuccess SUCCESS, + IFailure FAILURE) { + this.URL = URL; + this.PARAMS = PARAMS; + this.REQUEST = REQUEST; + this.DOWNLOAD_DIR = DOWNLOAD_DIR; + this.EXTENSION = EXTENSION; + this.NAME = NAME; + this.ERROR = ERROR; + this.SUCCESS = SUCCESS; + this.FAILURE = FAILURE; + } + + public final void handlerDownload() { + + if (REQUEST != null) { + REQUEST.onRequestStart(); + } + + RestCreator.getRestService().download(URL, PARAMS).enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + + if (response.isSuccessful()) { + final ResponseBody responseBody = response.body(); + final SaveFileTask task = new SaveFileTask(REQUEST, SUCCESS); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, DOWNLOAD_DIR, EXTENSION, response, NAME); + if (task.isCancelled()) { + if (REQUEST != null) { + REQUEST.onRequestEnd(); + } + } + } else { + if (ERROR != null) { + ERROR.onError(response.code(), response.message()); + } + } + + } + + @Override + public void onFailure(Call call, Throwable t) { + + if (FAILURE != null) { + FAILURE.onFailure(); + } + + } + }); + + } + +} diff --git a/vector_common/src/main/java/com/vector/common/net/download/SaveFileTask.java b/vector_common/src/main/java/com/vector/common/net/download/SaveFileTask.java new file mode 100644 index 0000000..ebcc336 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/net/download/SaveFileTask.java @@ -0,0 +1,76 @@ +package com.vector.common.net.download; + +import android.content.Intent; +import android.net.Uri; +import android.os.AsyncTask; + + +import com.vector.common.app.Vector; +import com.vector.common.net.callback.IRequest; +import com.vector.common.net.callback.ISuccess; +import com.vector.common.utils.storage.FileUtil; + +import java.io.File; +import java.io.InputStream; + +import okhttp3.ResponseBody; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +public class SaveFileTask extends AsyncTask { + + private final IRequest REQUEST; + private final ISuccess SUCCESS; + + public SaveFileTask(IRequest request, ISuccess success) { + this.REQUEST = request; + this.SUCCESS = success; + } + + @Override + protected File doInBackground(Object... params) { + + String downloadDir = (String) params[0]; + String extension = (String) params[1]; + final ResponseBody body = (ResponseBody) params[2]; + final String name = (String) params[3]; + final InputStream is = body.byteStream(); + if (downloadDir == null || downloadDir.equals("")) { + downloadDir = "down_loads"; + } + if (extension == null || extension.equals("")) { + extension = ""; + } + if (name == null) { + return FileUtil.writeToDisk(is, downloadDir, extension.toUpperCase(), extension); + } else { + return FileUtil.writeToDisk(is, downloadDir, name); + } + + } + + @Override + protected void onPostExecute(File file) { + super.onPostExecute(file); + if (SUCCESS != null) { + SUCCESS.onSuccess(file.getPath()); + } + if (REQUEST != null) { + REQUEST.onRequestEnd(); + } + } + + private void autoInstallApk(File file) { + + if (FileUtil.getExtension(file.getPath()).equals("apk")) { + final Intent install = new Intent(); + install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + install.setAction(Intent.ACTION_VIEW); + install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); + Vector.getApplicationContext().startActivity(install); + } + + } +} diff --git a/vector_common/src/main/java/com/vector/common/ui/loader/LoaderCreator.java b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderCreator.java new file mode 100644 index 0000000..e04e9d5 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderCreator.java @@ -0,0 +1,53 @@ +package com.vector.common.ui.loader; + +import android.content.Context; + +import com.wang.avi.AVLoadingIndicatorView; +import com.wang.avi.Indicator; + +import java.util.WeakHashMap; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +public class LoaderCreator { + + private static final WeakHashMap LOADING_MAP = new WeakHashMap<>(); + + static AVLoadingIndicatorView create(String type, Context context) { + + final AVLoadingIndicatorView avLoadingIndicatorView = new AVLoadingIndicatorView(context); + if (LOADING_MAP.get(type) == null) { + final Indicator indicator = getIndicator(type); + LOADING_MAP.put(type, indicator); + } + avLoadingIndicatorView.setIndicator(LOADING_MAP.get(type)); + return avLoadingIndicatorView; + + } + + private static Indicator getIndicator(String name) { + + if (name == null || name.isEmpty()) { + return null; + } + final StringBuilder drawableClassName = new StringBuilder(); + if (!name.contains(".")) { + final String defaultPackageName = AVLoadingIndicatorView.class.getPackage().getName(); + drawableClassName.append(defaultPackageName) + .append(".indicators") + .append("."); + } + drawableClassName.append(name); + try { + final Class drawableClass = Class.forName(drawableClassName.toString()); + return (Indicator) drawableClass.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + } + +} diff --git a/vector_common/src/main/java/com/vector/common/ui/loader/LoaderManager.java b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderManager.java new file mode 100644 index 0000000..95ecefc --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderManager.java @@ -0,0 +1,70 @@ +package com.vector.common.ui.loader; + +import android.content.Context; +import android.view.Gravity; +import android.view.Window; +import android.view.WindowManager; + + +import androidx.appcompat.app.AppCompatDialog; + +import com.vector.common.R; +import com.vector.common.utils.display.DimenUtil; +import com.wang.avi.AVLoadingIndicatorView; +import com.wang.avi.indicators.BallPulseIndicator; + +import java.util.ArrayList; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +public class LoaderManager { + + private static final int LOADER_SIZE_SCALE = 15; + private static final int LOADER_OFFSET_SCALE = 15; + + private static final ArrayList LOADERS = new ArrayList<>(); + + private static final String DEFAULT_LOADER = LoaderStyle.BallSpinFadeLoaderIndicator.name(); + + public static void showLoading(Context context, String type) { + + final AppCompatDialog dialog = new AppCompatDialog(context, R.style.loader_dialog); + + final AVLoadingIndicatorView avLoadingIndicatorView = LoaderCreator.create(type, context); + dialog.setContentView(avLoadingIndicatorView); + + int deviceWidth = DimenUtil.getScreenWidth(); + int deviceHeight = DimenUtil.getScreenHeight(); + final Window dialogWindow = dialog.getWindow(); + + if (dialogWindow != null) { + WindowManager.LayoutParams lp = dialogWindow.getAttributes(); + lp.width = deviceWidth / LOADER_SIZE_SCALE; + lp.height = deviceHeight / LOADER_SIZE_SCALE + deviceHeight / LOADER_OFFSET_SCALE; + lp.gravity = Gravity.CENTER; + } + LOADERS.add(dialog); + dialog.show(); + + } + + public static void showLoading(Context context, LoaderStyle loaderStyle) { + showLoading(context, loaderStyle.name()); + } + + public static void showLoading(Context context) { + showLoading(context, DEFAULT_LOADER); + } + + public static void stopLoading() { + for (AppCompatDialog dialog : LOADERS) { + if (dialog != null) { + if (dialog.isShowing()) { + dialog.dismiss(); + } + } + } + } +} diff --git a/vector_common/src/main/java/com/vector/common/ui/loader/LoaderStyle.java b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderStyle.java new file mode 100644 index 0000000..bfc11d1 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/ui/loader/LoaderStyle.java @@ -0,0 +1,38 @@ +package com.vector.common.ui.loader; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +@SuppressWarnings("unused") +public enum LoaderStyle { + BallPulseIndicator, + BallGridPulseIndicator, + BallClipRotateIndicator, + BallClipRotatePulseIndicator, + SquareSpinIndicator, + BallClipRotateMultipleIndicator, + BallPulseRiseIndicator, + BallRotateIndicator, + CubeTransitionIndicator, + BallZigZagIndicator, + BallZigZagDeflectIndicator, + BallTrianglePathIndicator, + BallScaleIndicator, + LineScaleIndicator, + LineScalePartyIndicator, + BallScaleMultipleIndicator, + BallPulseSyncIndicator, + BallBeatIndicator, + LineScalePulseOutIndicator, + LineScalePulseOutRapidIndicator, + BallScaleRippleIndicator, + BallScaleRippleMultipleIndicator, + BallSpinFadeLoaderIndicator, + LineSpinFadeLoaderIndicator, + TriangleSkewSpinIndicator, + PacmanIndicator, + BallGridBeatIndicator, + SemiCircleSpinIndicator, + CustomIndicator +} diff --git a/vector_common/src/main/java/com/vector/common/utils/display/DimenUtil.java b/vector_common/src/main/java/com/vector/common/utils/display/DimenUtil.java new file mode 100644 index 0000000..9584923 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/utils/display/DimenUtil.java @@ -0,0 +1,30 @@ +package com.vector.common.utils.display; + +import android.content.res.Resources; +import android.util.DisplayMetrics; +import android.util.Log; + +import com.vector.common.app.Vector; + +/** + * Created by 瓮少波 on 2018/4/25. + */ + +public class DimenUtil { + + public static int getScreenWidth() { + final Resources resources = Vector.getApplicationContext().getResources(); + final DisplayMetrics dm = resources.getDisplayMetrics(); + return dm.widthPixels; + } + + + public static int getScreenHeight() { + final Resources resources = Vector.getApplicationContext().getResources(); + final DisplayMetrics dm = resources.getDisplayMetrics(); + return dm.heightPixels; + } + + ; + +} diff --git a/vector_common/src/main/java/com/vector/common/utils/log/LoggerUtil.java b/vector_common/src/main/java/com/vector/common/utils/log/LoggerUtil.java new file mode 100644 index 0000000..6c5df97 --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/utils/log/LoggerUtil.java @@ -0,0 +1,79 @@ +package com.vector.common.utils.log; + +import android.util.Log; + +import com.orhanobut.logger.Logger; +import com.vector.common.BuildConfig; +import com.vector.common.app.ConfigType; +import com.vector.common.app.Vector; + +/** + * @author Vector Weng + * @description: 日志工具类 + * @date :2020/12/22 18:41 + */ +public class LoggerUtil { + + private static final String TAG = LoggerUtil.class.getSimpleName(); + + public static class LoggerLevel { + public static final int VERBOSE = 1; + public static final int DEBUG = 2; + public static final int INFO = 3; + public static final int WARN = 4; + public static final int ERROR = 5; + public static final int NOTHING = 6; + } + + private static Integer LOG_LEVEL = Vector.getConfiguration(ConfigType.LOGGER_LEVEL); + + private static Integer checkLoggerLevel() { + if (LOG_LEVEL == null) { + Log.e(TAG, "Vector_CommonLibrary----------Logger is not init"); + } + return LOG_LEVEL; + } + + public static void v(String tag, String message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.VERBOSE) { + Logger.t(tag).v(message); + } + } + + public static void d(String tag, Object message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.DEBUG) { + Logger.t(tag).d(message); + } + } + + public static void d(Object message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.DEBUG) { + Logger.d(message); + } + } + + public static void i(String tag, String message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.INFO) { + Logger.t(tag).i(message); + } + } + + public static void w(String tag, String message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.WARN) { + Logger.t(tag).w(message); + } + } + + public static void json(String tag, String message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.WARN) { + Logger.t(tag).json(message); + } + } + + public static void e(String tag, String message) { + if (checkLoggerLevel() != null && checkLoggerLevel() <= LoggerLevel.ERROR) { + Logger.t(tag).e(message); + } + } + +} diff --git a/vector_common/src/main/java/com/vector/common/utils/storage/FileUtil.java b/vector_common/src/main/java/com/vector/common/utils/storage/FileUtil.java new file mode 100644 index 0000000..172941c --- /dev/null +++ b/vector_common/src/main/java/com/vector/common/utils/storage/FileUtil.java @@ -0,0 +1,367 @@ +package com.vector.common.utils.storage; + +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Typeface; +import android.media.MediaScannerConnection; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.MediaStore; +import android.webkit.MimeTypeMap; +import android.widget.TextView; + + +import com.vector.common.app.Vector; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + + +public final class FileUtil { + + //格式化的模板 + private static final String TIME_FORMAT = "_yyyyMMdd_HHmmss"; + + private static final String SDCARD_DIR = + Environment.getExternalStorageDirectory().getPath(); + + //默认本地上传图片目录 + public static final String UPLOAD_PHOTO_DIR = + Environment.getExternalStorageDirectory().getPath() + "/a_upload_photos/"; + + //网页缓存地址 + public static final String WEB_CACHE_DIR = + Environment.getExternalStorageDirectory().getPath() + "/app_web_cache/"; + + //系统相机目录 + public static final String CAMERA_PHOTO_DIR = + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/Camera/"; + + private static String getTimeFormatName(String timeFormatHeader) { + final Date date = new Date(System.currentTimeMillis()); + //必须要加上单引号 + final SimpleDateFormat dateFormat = new SimpleDateFormat("'" + timeFormatHeader + "'" + TIME_FORMAT, Locale.getDefault()); + return dateFormat.format(date); + } + + /** + * @param timeFormatHeader 格式化的头(除去时间部分) + * @param extension 后缀名 + * @return 返回时间格式化后的文件名 + */ + public static String getFileNameByTime(String timeFormatHeader, String extension) { + return getTimeFormatName(timeFormatHeader) + "." + extension; + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + private static File createDir(String sdcardDirName) { + //拼接成SD卡中完整的dir + final String dir = SDCARD_DIR + "/" + sdcardDirName + "/"; + final File fileDir = new File(dir); + if (!fileDir.exists()) { + fileDir.mkdirs(); + } + return fileDir; + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public static File createFile(String sdcardDirName, String fileName) { + return new File(createDir(sdcardDirName), fileName); + } + + private static File createFileByTime(String sdcardDirName, String timeFormatHeader, String extension) { + final String fileName = getFileNameByTime(timeFormatHeader, extension); + return createFile(sdcardDirName, fileName); + } + + //获取文件的MIME + public static String getMimeType(String filePath) { + final String extension = getExtension(filePath); + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + } + + //获取文件的后缀名 + public static String getExtension(String filePath) { + String suffix = ""; + final File file = new File(filePath); + final String name = file.getName(); + final int idx = name.lastIndexOf('.'); + if (idx > 0) { + suffix = name.substring(idx + 1); + } + return suffix; + } + + /** + * 保存Bitmap到SD卡中 + * + * @param dir 目录名,只需要写自己的相对目录名即可 + * @param compress 压缩比例 100是不压缩,值约小压缩率越高 + * @return 返回该文件 + */ + public static File saveBitmap(Bitmap mBitmap, String dir, int compress) { + + final String sdStatus = Environment.getExternalStorageState(); + // 检测sd是否可用 + if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { + return null; + } + FileOutputStream fos = null; + BufferedOutputStream bos = null; + File fileName = createFileByTime(dir, "DOWN_LOAD", "jpg"); + try { + fos = new FileOutputStream(fileName); + bos = new BufferedOutputStream(fos); + mBitmap.compress(Bitmap.CompressFormat.JPEG, compress, bos);// 把数据写入文件 + } catch (FileNotFoundException e) { + e.printStackTrace(); + } finally { + try { + + if (bos != null) { + bos.flush(); + } + if (bos != null) { + bos.close(); + } + //关闭流 + if (fos != null) { + fos.flush(); + } + if (fos != null) { + fos.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + refreshDCIM(); + + return fileName; + } + + public static File writeToDisk(InputStream is, String dir, String name) { + final File file = FileUtil.createFile(dir, name); + BufferedInputStream bis = null; + FileOutputStream fos = null; + BufferedOutputStream bos = null; + + try { + bis = new BufferedInputStream(is); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + + byte data[] = new byte[1024 * 4]; + + int count; + while ((count = bis.read(data)) != -1) { + bos.write(data, 0, count); + } + + bos.flush(); + fos.flush(); + + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (bos != null) { + bos.close(); + } + if (fos != null) { + fos.close(); + } + if (bis != null) { + bis.close(); + } + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return file; + } + + public static File writeToDisk(InputStream is, String dir, String prefix, String extension) { + final File file = FileUtil.createFileByTime(dir, prefix, extension); + BufferedInputStream bis = null; + FileOutputStream fos = null; + BufferedOutputStream bos = null; + + try { + bis = new BufferedInputStream(is); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + + byte data[] = new byte[1024 * 4]; + + int count; + while ((count = bis.read(data)) != -1) { + bos.write(data, 0, count); + } + + bos.flush(); + fos.flush(); + + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (bos != null) { + bos.close(); + } + if (fos != null) { + fos.close(); + } + if (bis != null) { + bis.close(); + } + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return file; + } + + /** + * 通知系统刷新系统相册,使照片展现出来 + */ + private static void refreshDCIM() { + if (Build.VERSION.SDK_INT >= 19) { + //兼容android4.4版本,只扫描存放照片的目录 + MediaScannerConnection.scanFile(Vector.getApplicationContext(), + new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()}, + null, null); + } else { + //扫描整个SD卡来更新系统图库,当文件很多时用户体验不佳,且不适合4.4以上版本 + Vector.getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + + Environment.getExternalStorageDirectory()))); + } + } + + /** + * 读取raw目录中的文件,并返回为字符串 + */ + public static String getRawFile(int id) { + final InputStream is = Vector.getApplicationContext().getResources().openRawResource(id); + final BufferedInputStream bis = new BufferedInputStream(is); + final InputStreamReader isr = new InputStreamReader(bis); + final BufferedReader br = new BufferedReader(isr); + final StringBuilder stringBuilder = new StringBuilder(); + String str; + try { + while ((str = br.readLine()) != null) { + stringBuilder.append(str); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + isr.close(); + bis.close(); + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return stringBuilder.toString(); + } + + + public static void setIconFont(String path, TextView textView) { + final Typeface typeface = Typeface.createFromAsset(Vector.getApplicationContext().getAssets(), path); + textView.setTypeface(typeface); + } + + /** + * 读取assets目录下的文件,并返回字符串 + */ + public static String getAssetsFile(String name) { + InputStream is = null; + BufferedInputStream bis = null; + InputStreamReader isr = null; + BufferedReader br = null; + StringBuilder stringBuilder = null; + final AssetManager assetManager = Vector.getApplicationContext().getAssets(); + try { + is = assetManager.open(name); + bis = new BufferedInputStream(is); + isr = new InputStreamReader(bis); + br = new BufferedReader(isr); + stringBuilder = new StringBuilder(); + String str; + while ((str = br.readLine()) != null) { + stringBuilder.append(str); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) { + br.close(); + } + if (isr != null) { + isr.close(); + } + if (bis != null) { + bis.close(); + } + if (is != null) { + is.close(); + } + assetManager.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (stringBuilder != null) { + return stringBuilder.toString(); + } else { + return null; + } + } + + public static String getRealFilePath(final Context context, final Uri uri) { + if (null == uri) return null; + final String scheme = uri.getScheme(); + String data = null; + if (scheme == null) + data = uri.getPath(); + else if (ContentResolver.SCHEME_FILE.equals(scheme)) { + data = uri.getPath(); + } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { + final Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); + if (null != cursor) { + if (cursor.moveToFirst()) { + final int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); + if (index > -1) { + data = cursor.getString(index); + } + } + cursor.close(); + } + } + return data; + } +} diff --git a/vector_common/src/main/res/values/ids.xml b/vector_common/src/main/res/values/ids.xml new file mode 100644 index 0000000..c098bc3 --- /dev/null +++ b/vector_common/src/main/res/values/ids.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/vector_common/src/main/res/values/style.xml b/vector_common/src/main/res/values/style.xml new file mode 100644 index 0000000..fbedb31 --- /dev/null +++ b/vector_common/src/main/res/values/style.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file