MVPArms实现本现数据缓存
生活随笔
收集整理的這篇文章主要介紹了
MVPArms实现本现数据缓存
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
找到app下GlobalConfiguration類,將以下類替換即可實現緩存(文件路徑需手動更改)package
MVPArms https://github.com/JessYanCoding/MVPArms
package com.mygz.inspect.app;import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager;import com.gzny.inspect.BuildConfig; import com.gzny.inspect.app.ActivityLifecycleCallbacksImpl; import com.gzny.inspect.app.AppLifecyclesImpl; import com.gzny.inspect.app.FragmentLifecycleCallbacksImpl; import com.gzny.inspect.app.GlobalHttpHandlerImpl; import com.gzny.inspect.app.ResponseErrorListenerImpl; import com.gzny.inspect.mvp.model.api.Api; import com.jess.arms.base.delegate.AppLifecycles; import com.jess.arms.di.module.GlobalConfigModule; import com.jess.arms.http.imageloader.glide.GlideImageLoaderStrategy; import com.jess.arms.http.log.RequestInterceptor; import com.jess.arms.integration.ConfigModule; import com.jess.arms.utils.ArmsUtils; import com.squareup.leakcanary.RefWatcher;import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit;import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response;/*** ================================================* App 的全局配置信息在此配置, 需要將此實現類聲明到 AndroidManifest 中* ConfigModule 的實現類可以有無數多個, 在 Application 中只是注冊回調, 并不會影響性能 (多個 ConfigModule 在多 Module 環境下尤為受用)** @see com.jess.arms.base.delegate.AppDelegate* @see com.jess.arms.integration.ManifestParser* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki">請配合官方 Wiki 文檔學習本框架</a>* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/UpdateLog">更新日志, 升級必看!</a>* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/Issues">常見 Issues, 踩坑必看!</a>* @see <a href="https://github.com/JessYanCoding/ArmsComponent/wiki">MVPArms 官方組件化方案 ArmsComponent, 進階指南!</a>* Created by MVPArmsTemplate on 01/19/2019 20:16* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>* <a href="https://github.com/JessYanCoding">Follow me</a>* ================================================*/ public final class GlobalConfiguration implements ConfigModule { // public static String sDomain = Api.APP_DOMAIN;@Overridepublic void applyOptions(Context context, GlobalConfigModule.Builder builder) {if (!BuildConfig.LOG_DEBUG) { //Release 時, 讓框架不再打印 Http 請求和響應的信息builder.printHttpLogLevel(RequestInterceptor.Level.NONE);}builder.baseurl(Api.APP_DOMAIN)//強烈建議自己自定義圖片加載邏輯, 因為 arms-imageloader-glide 提供的 GlideImageLoaderStrategy 并不能滿足復雜的需求//請參考 https://github.com/JessYanCoding/MVPArms/wiki#3.4.imageLoaderStrategy(new GlideImageLoaderStrategy())//想支持多 BaseUrl, 以及運行時動態切換任意一個 BaseUrl, 請使用 https://github.com/JessYanCoding/RetrofitUrlManager//如果 BaseUrl 在 App 啟動時不能確定, 需要請求服務器接口動態獲取, 請使用以下代碼//以下方式是 Arms 框架自帶的切換 BaseUrl 的方式, 在整個 App 生命周期內只能切換一次, 若需要無限次的切換 BaseUrl, 以及各種復雜的應用場景還是需要使用 RetrofitUrlManager 框架//以下代碼只是配置, 還要使用 Okhttp (AppComponent 中提供) 請求服務器獲取到正確的 BaseUrl 后賦值給 GlobalConfiguration.sDomain//切記整個過程必須在第一次調用 Retrofit 接口之前完成, 如果已經調用過 Retrofit 接口, 此種方式將不能切換 BaseUrl // .baseurl(new BaseUrl() { // @Override // public HttpUrl url() { // return HttpUrl.parse(sDomain); // } // })//可根據當前項目的情況以及環境為框架某些部件提供自定義的緩存策略, 具有強大的擴展性 // .cacheFactory(new Cache.Factory() { // @NonNull // @Override // public Cache build(CacheType type) { // switch (type.getCacheTypeId()){ // case CacheType.EXTRAS_TYPE_ID: // return new IntelligentCache(500); // case CacheType.CACHE_SERVICE_CACHE_TYPE_ID: // return new Cache(type.calculateCacheSize(context));//自定義 Cache // default: // return new LruCache(200); // } // } // })//若覺得框架默認的打印格式并不能滿足自己的需求, 可自行擴展自己理想的打印格式 (以下只是簡單實現) // .formatPrinter(new FormatPrinter() { // @Override // public void printJsonRequest(Request request, String bodyString) { // Timber.i("printJsonRequest:" + bodyString); // } // // @Override // public void printFileRequest(Request request) { // Timber.i("printFileRequest:" + request.url().toString()); // } // // @Override // public void printJsonResponse(long chainMs, boolean isSuccessful, int code, // String headers, MediaType contentType, String bodyString, // List<String> segments, String message, String responseUrl) { // Timber.i("printJsonResponse:" + bodyString); // } // // @Override // public void printFileResponse(long chainMs, boolean isSuccessful, int code, String headers, // List<String> segments, String message, String responseUrl) { // Timber.i("printFileResponse:" + responseUrl); // } // })//可以自定義一個單例的線程池供全局使用 // .executorService(Executors.newCachedThreadPool())//這里提供一個全局處理 Http 請求和響應結果的處理類, 可以比客戶端提前一步拿到服務器返回的結果, 可以做一些操作, 比如 Token 超時后, 重新獲取 Token.globalHttpHandler(new GlobalHttpHandlerImpl(context))//用來處理 RxJava 中發生的所有錯誤, RxJava 中發生的每個錯誤都會回調此接口//RxJava 必須要使用 ErrorHandleSubscriber (默認實現 Subscriber 的 onError 方法), 此監聽才生效.responseErrorListener(new ResponseErrorListenerImpl()).gsonConfiguration((context1, gsonBuilder) -> {//這里可以自己自定義配置 Gson 的參數gsonBuilder.serializeNulls()//支持序列化值為 null 的參數.enableComplexMapKeySerialization();//支持將序列化 key 為 Object 的 Map, 默認只能序列化 key 為 String 的 Map}).retrofitConfiguration((context1, retrofitBuilder) -> {//這里可以自己自定義配置 Retrofit 的參數, 甚至您可以替換框架配置好的 OkHttpClient 對象 (但是不建議這樣做, 這樣做您將損失框架提供的很多功能) // retrofitBuilder.addConverterFactory(FastJsonConverterFactory.create());//比如使用 FastJson 替代 Gson}).okhttpConfiguration((context1, okhttpBuilder) -> {//這里可以自己自定義配置 Okhttp 的參數 // okhttpBuilder.sslSocketFactory(); //支持 Https, 詳情請百度//okhttpBuilder.writeTimeout(10, TimeUnit.SECONDS);File cacheFile = new File(context.getExternalCacheDir(),"tangnuer");Cache cache = new Cache(cacheFile,1024*1024*50);okhttpBuilder.cache(cache).addNetworkInterceptor(new HttpCaCheInterceper()).build();//使用一行代碼監聽 Retrofit/Okhttp 上傳下載進度監聽, 以及 Glide 加載進度監聽, 詳細使用方法請查看 https://github.com/JessYanCoding/ProgressManager // ProgressManager.getInstance().with(okhttpBuilder);//讓 Retrofit 同時支持多個 BaseUrl 以及動態改變 BaseUrl, 詳細使用方法請查看 https://github.com/JessYanCoding/RetrofitUrlManager // RetrofitUrlManager.getInstance().with(okhttpBuilder);}).rxCacheConfiguration((context1, rxCacheBuilder) -> {//這里可以自己自定義配置 RxCache 的參數rxCacheBuilder.useExpiredDataIfLoaderNotAvailable(true);//想自定義 RxCache 的緩存文件夾或者解析方式, 如改成 FastJson, 請 return rxCacheBuilder.persistence(cacheDirectory, new FastJsonSpeaker());//否則請 return null;return null;});}@Overridepublic void injectAppLifecycle(Context context, List<AppLifecycles> lifecycles) {//AppLifecycles 中的所有方法都會在基類 Application 的對應生命周期中被調用, 所以在對應的方法中可以擴展一些自己需要的邏輯//可以根據不同的邏輯添加多個實現類lifecycles.add(new AppLifecyclesImpl());}@Overridepublic void injectActivityLifecycle(Context context, List<Application.ActivityLifecycleCallbacks> lifecycles) {//ActivityLifecycleCallbacks 中的所有方法都會在 Activity (包括三方庫) 的對應生命周期中被調用, 所以在對應的方法中可以擴展一些自己需要的邏輯//可以根據不同的邏輯添加多個實現類lifecycles.add(new ActivityLifecycleCallbacksImpl());}@Overridepublic void injectFragmentLifecycle(Context context, List<FragmentManager.FragmentLifecycleCallbacks> lifecycles) {//FragmentLifecycleCallbacks 中的所有方法都會在 Fragment (包括三方庫) 的對應生命周期中被調用, 所以在對應的方法中可以擴展一些自己需要的邏輯//可以根據不同的邏輯添加多個實現類lifecycles.add(new FragmentLifecycleCallbacksImpl());}private class HttpCaCheInterceper implements Interceptor{@Overridepublic Response intercept(Chain chain) throws IOException {Request request = chain.request();Response response = chain.proceed(request);//無網絡緩存到本地,保存時間(30天)Response response1 = response.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "max-age=" + 3600 * 24 * 30).build();return response1;}} }總結
以上是生活随笔為你收集整理的MVPArms实现本现数据缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在navicat中新建数据库
- 下一篇: java7 3dm下载_3DM游戏运行库