diff --git a/app/proguard-rules.txt b/app/proguard-rules.txt index 157796ab3e..5d34235bc6 100644 --- a/app/proguard-rules.txt +++ b/app/proguard-rules.txt @@ -16,9 +16,23 @@ # public *; #} +#--------- remove logs start ---------------- +-assumenosideeffects class com.lightgame.config.CommonDebug { + private static String getLogTag(...); + private static String getMethodName(); + public static void logMethodName(...); + public static void logParams(...); + public static void logFields(...); + public static void logMethodWithParams(...); +} + +#-assumenosideeffects class com.lightgame.config.CommonDebug {*;} + +#-dontoptimize +#--------- remove logs end ---------------- + -keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod -dontwarn InnerClasses --dontoptimize # OrmLite uses reflection -keep class com.j256.** diff --git a/app/src/main/java/com/gh/base/AppController.java b/app/src/main/java/com/gh/base/AppController.java index 5c63d9370c..fd10406e12 100644 --- a/app/src/main/java/com/gh/base/AppController.java +++ b/app/src/main/java/com/gh/base/AppController.java @@ -2,10 +2,9 @@ package com.gh.base; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; -import android.app.Application; import android.content.Context; import android.os.Process; -import android.support.multidex.MultiDex; +import android.support.multidex.MultiDexApplication; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.util.Log; @@ -18,6 +17,7 @@ import com.gh.common.util.StringUtils; import com.gh.common.util.TokenUtils; import com.gh.gamecenter.BuildConfig; import com.leon.channel.helper.ChannelReaderUtil; +import com.lightgame.config.CommonDebug; import com.lightgame.utils.Utils; import com.umeng.message.IUmengRegisterCallback; import com.umeng.message.PushAgent; @@ -33,9 +33,8 @@ import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; -public class AppController extends Application { +public class AppController extends MultiDexApplication { - public static final String TAG = AppController.class.getSimpleName(); public static final String KEY_FILE_INFO = "FileInfo"; //快传文件发送单线程 public static Executor FILE_SENDER_EXECUTOR = Executors.newSingleThreadExecutor(); @@ -79,12 +78,6 @@ public class AppController extends Application { return mChannel; } - @Override - protected void attachBaseContext(Context base) { - super.attachBaseContext(base); - MultiDex.install(this); - } - @Override public void onCreate() { super.onCreate(); @@ -139,17 +132,17 @@ public class AppController extends Application { @Override public void setTag(String tag) { - // ignore + CommonDebug.logMethodWithParams(this, tag); } @Override public void log(String content) { - Log.d(TAG, content); + CommonDebug.logMethodWithParams(this, content); } @Override public void log(String content, Throwable t) { - Log.d(TAG, content, t); + CommonDebug.logMethodWithParams(this, content, t); } }; Logger.setLogger(this, newLogger); @@ -158,6 +151,7 @@ public class AppController extends Application { try { //友盟推送 final PushAgent pushAgent = PushAgent.getInstance(this); + pushAgent.setDebugMode(false); pushAgent.setAppkeyAndSecret(Config.UMENG_APPKEY, Config.UMENG_MESSAGE_SECRET); //注册推送服务,每次调用register方法都会回调该接口 @@ -209,17 +203,16 @@ public class AppController extends Application { // } // } - // 启用EventBus3.0加速功能 - EventBus.builder().addIndex(new EventBusIndex()).installDefaultEventBus(); - } + // 启用EventBus3.0加速功能 + EventBus.builder().addIndex(new EventBusIndex()).installDefaultEventBus(); + } private boolean shouldInit() { ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); - List processInfos = am.getRunningAppProcesses(); + List processInfoList = am.getRunningAppProcesses(); String mainProcessName = getPackageName(); - Log.d(TAG, mainProcessName); int myPid = Process.myPid(); - for (RunningAppProcessInfo info : processInfos) { + for (RunningAppProcessInfo info : processInfoList) { if (info.pid == myPid && mainProcessName.equals(info.processName)) { return true; } diff --git a/app/src/main/java/com/gh/download/DownloadManager.java b/app/src/main/java/com/gh/download/DownloadManager.java index 352cdd029c..b866e63785 100644 --- a/app/src/main/java/com/gh/download/DownloadManager.java +++ b/app/src/main/java/com/gh/download/DownloadManager.java @@ -19,6 +19,7 @@ import com.gh.gamecenter.entity.ApkEntity; import com.gh.gamecenter.entity.GameEntity; import com.gh.gamecenter.eventbus.EBDownloadStatus; import com.gh.gamecenter.manager.PackageManager; +import com.lightgame.config.CommonDebug; import com.lightgame.download.ConnectionUtils; import com.lightgame.download.DataChanger; import com.lightgame.download.DataWatcher; @@ -387,7 +388,9 @@ public class DownloadManager implements DownloadStatusListener { * @return null表示没有下载任务 */ public List getAll() { - Utils.log(DownloadManager.class.getSimpleName(), "getAll"); + if (CommonDebug.IS_DEBUG) { + CommonDebug.logMethodName(this); + } return mDownloadDao.getAll(); } diff --git a/app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java b/app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java index 7dc222bf4b..52bdca12ad 100644 --- a/app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java +++ b/app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java @@ -442,8 +442,8 @@ public class MessageDetailActivity extends BaseActivity implements OnCommentCall // 完成评论操作,添加评论数 adapter.addCommentCount(); //修改评论缓存 - CommentManager.updateOkhttpCacheForId(newsId); - CommentManager.updateOkhttpCache(newsId); + CommentManager.updateOkhttpCacheForId(MessageDetailActivity.this, newsId); + CommentManager.updateOkhttpCache(MessageDetailActivity.this, newsId); adapter.notifyItemInserted(adapter.getHotCommentListSize() + 2); adapter.notifyItemChanged(adapter.getItemCount() - 1); //刷新脚布局高度 } else { @@ -497,7 +497,7 @@ public class MessageDetailActivity extends BaseActivity implements OnCommentCall private void modifyNewsCommentOkhttpCache(int offset, JSONObject commentData, String id) { String key = TimestampUtils.addTimestamp(Config.COMMENT_HOST + "article/" + id + "/comment?limit=10&offset=" + offset); - byte[] data = OkHttpCache.getCache(key); + byte[] data = OkHttpCache.getCache(this, key); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(data)); @@ -506,7 +506,7 @@ public class MessageDetailActivity extends BaseActivity implements OnCommentCall for (int i = 0, size = jsonArray.length() > 9 ? 9 : jsonArray.length(); i < size; i++) { newComment.put(jsonArray.get(i)); } - OkHttpCache.updateCache(key, newComment.toString().getBytes()); + OkHttpCache.updateCache(this, key, newComment.toString().getBytes()); if (jsonArray.length() == 10) { modifyNewsCommentOkhttpCache(offset + 10, jsonArray.getJSONObject(9), id); } diff --git a/app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java b/app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java index d1ebcd2ca0..0e9efd3a82 100644 --- a/app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java +++ b/app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java @@ -1,6 +1,5 @@ package com.gh.gamecenter.adapter; -import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; @@ -14,7 +13,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; -import com.lightgame.adapter.BaseRecyclerAdapter; import com.gh.common.constant.Config; import com.gh.common.util.CommentUtils; import com.gh.common.util.ConcernContentUtils; @@ -538,7 +536,7 @@ public class MessageDetailAdapter extends BaseRecyclerAdapter { notifyItemChanged(0); // 更新okhttp缓存数据 - VisitManager.updateOkhttpCache(mConcernEntity.getId()); + VisitManager.updateOkhttpCache(mContext, mConcernEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); @@ -553,7 +551,7 @@ public class MessageDetailAdapter extends BaseRecyclerAdapter { return; } url = TimestampUtils.addTimestamp(url); - byte[] data = OkHttpCache.getCache(url); + byte[] data = OkHttpCache.getCache(mContext, url); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(data)); @@ -565,7 +563,7 @@ public class MessageDetailAdapter extends BaseRecyclerAdapter { break; } } - OkHttpCache.updateCache(url, jsonArray.toString().getBytes()); + OkHttpCache.updateCache(mContext, url, jsonArray.toString().getBytes()); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/com/gh/gamecenter/collection/ArticleAdapter.java b/app/src/main/java/com/gh/gamecenter/collection/ArticleAdapter.java index 40cfa25d7f..7ab46a84e0 100644 --- a/app/src/main/java/com/gh/gamecenter/collection/ArticleAdapter.java +++ b/app/src/main/java/com/gh/gamecenter/collection/ArticleAdapter.java @@ -262,7 +262,7 @@ public class ArticleAdapter extends BaseRecyclerAdapter { notifyItemChanged(position); // 更新okhttp缓存数据 - VisitManager.updateOkhttpCache(newsEntity.getId()); + VisitManager.updateOkhttpCache(mContext, newsEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/com/gh/gamecenter/manager/CommentManager.java b/app/src/main/java/com/gh/gamecenter/manager/CommentManager.java index 9794f0fadb..006605c8a0 100644 --- a/app/src/main/java/com/gh/gamecenter/manager/CommentManager.java +++ b/app/src/main/java/com/gh/gamecenter/manager/CommentManager.java @@ -1,5 +1,7 @@ package com.gh.gamecenter.manager; +import android.content.Context; + import com.gh.common.constant.Config; import com.gh.common.util.StringUtils; import com.gh.common.util.TimestampUtils; @@ -28,7 +30,7 @@ public class CommentManager { } // 更新okhttp缓存数据 修改资讯关注列表评论数 ids - public static void updateOkhttpCache(final String comment_id) { + public static void updateOkhttpCache(final Context context, final String comment_id) { ObservableUtil.io(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { @@ -37,7 +39,7 @@ public class CommentManager { return; } key = TimestampUtils.addTimestamp(key); - byte[] data = OkHttpCache.getCache(key); + byte[] data = OkHttpCache.getCache(context, key); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(data)); @@ -49,7 +51,7 @@ public class CommentManager { break; } } - OkHttpCache.updateCache(key, jsonArray.toString().getBytes()); + OkHttpCache.updateCache(context, key, jsonArray.toString().getBytes()); } catch (JSONException e) { e.printStackTrace(); } @@ -79,12 +81,12 @@ public class CommentManager { } // 修改新闻详情评论数 id - public static void updateOkhttpCacheForId(final String comment_id) { + public static void updateOkhttpCacheForId(final Context context, final String comment_id) { ObservableUtil.io(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { String key = TimestampUtils.addTimestamp(StringUtils.buildString(Config.COMMENT_HOST, "article/", comment_id, "/comment/num")); - byte[] data = OkHttpCache.getCache(key); + byte[] data = OkHttpCache.getCache(context, key); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(data)); @@ -96,7 +98,7 @@ public class CommentManager { break; } } - OkHttpCache.updateCache(key, jsonArray.toString().getBytes()); + OkHttpCache.updateCache(context, key, jsonArray.toString().getBytes()); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/com/gh/gamecenter/manager/VisitManager.java b/app/src/main/java/com/gh/gamecenter/manager/VisitManager.java index 27d743747e..9eab8adf77 100644 --- a/app/src/main/java/com/gh/gamecenter/manager/VisitManager.java +++ b/app/src/main/java/com/gh/gamecenter/manager/VisitManager.java @@ -1,5 +1,7 @@ package com.gh.gamecenter.manager; +import android.content.Context; + import com.gh.common.constant.Config; import com.gh.common.util.StringUtils; import com.gh.common.util.TimestampUtils; @@ -29,7 +31,7 @@ public class VisitManager { } // 更新okhttp缓存数据 - public static void updateOkhttpCache(final String news_id) { + public static void updateOkhttpCache(final Context context, final String news_id) { ObservableUtil.io(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { @@ -38,7 +40,7 @@ public class VisitManager { return; } key = TimestampUtils.addTimestamp(key); - byte[] data = OkHttpCache.getCache(key); + byte[] data = OkHttpCache.getCache(context, key); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(data)); @@ -50,7 +52,7 @@ public class VisitManager { break; } } - OkHttpCache.updateCache(key, jsonArray.toString().getBytes()); + OkHttpCache.updateCache(context, key, jsonArray.toString().getBytes()); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java b/app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java index c9163e2451..d20132af19 100644 --- a/app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java +++ b/app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java @@ -270,7 +270,7 @@ public class News1FragmentAdapter extends BaseRecyclerAdapter { notifyItemChanged(position); // 更新okhttp缓存数据 - VisitManager.updateOkhttpCache(newsEntity.getId()); + VisitManager.updateOkhttpCache(mContext, newsEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/com/gh/gamecenter/news/News2FragmentAdapter.java b/app/src/main/java/com/gh/gamecenter/news/News2FragmentAdapter.java index ea518c7e02..715f83ffde 100644 --- a/app/src/main/java/com/gh/gamecenter/news/News2FragmentAdapter.java +++ b/app/src/main/java/com/gh/gamecenter/news/News2FragmentAdapter.java @@ -737,7 +737,7 @@ public class News2FragmentAdapter extends BaseRecyclerAdapter { notifyItemChanged(position); // 更新okhttp缓存数据 - VisitManager.updateOkhttpCache(concernEntity.getId()); + VisitManager.updateOkhttpCache(mContext, concernEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/com/gh/gamecenter/news/News4FragmentAdapter.java b/app/src/main/java/com/gh/gamecenter/news/News4FragmentAdapter.java index d288e112ce..6ab4f75b74 100644 --- a/app/src/main/java/com/gh/gamecenter/news/News4FragmentAdapter.java +++ b/app/src/main/java/com/gh/gamecenter/news/News4FragmentAdapter.java @@ -3,12 +3,12 @@ package com.gh.gamecenter.news; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.util.DisplayMetrics; -import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.Toast; +import com.gh.base.OnRequestCallBackListener; import com.gh.common.constant.ItemViewType; import com.gh.common.util.DataCollectionUtils; import com.gh.common.util.DataUtils; @@ -17,19 +17,18 @@ import com.gh.common.util.ImageUtils; import com.gh.common.util.NewsUtils; import com.gh.gamecenter.NewsDetailActivity; import com.gh.gamecenter.R; -import com.lightgame.adapter.BaseRecyclerAdapter; import com.gh.gamecenter.adapter.viewholder.FooterViewHolder; import com.gh.gamecenter.adapter.viewholder.NewsImage1ViewHolder; import com.gh.gamecenter.adapter.viewholder.NewsImage2ViewHolder; import com.gh.gamecenter.adapter.viewholder.NewsImage3ViewHolder; import com.gh.gamecenter.entity.NewsEntity; import com.gh.gamecenter.entity.ViewsEntity; -import com.gh.base.OnRequestCallBackListener; import com.gh.gamecenter.manager.VisitManager; import com.gh.gamecenter.retrofit.JSONObjectResponse; import com.gh.gamecenter.retrofit.ObservableUtil; import com.gh.gamecenter.retrofit.Response; import com.gh.gamecenter.retrofit.RetrofitManager; +import com.lightgame.adapter.BaseRecyclerAdapter; import org.json.JSONException; import org.json.JSONObject; @@ -84,20 +83,16 @@ public class News4FragmentAdapter extends BaseRecyclerAdapter { View view; switch (viewType) { case ItemViewType.NEWS_IMAGE1: - view = LayoutInflater.from(parent.getContext()).inflate( - R.layout.news_image1_item, parent, false); + view = mLayoutInflater.inflate(R.layout.news_image1_item, parent, false); return new NewsImage1ViewHolder(view); case ItemViewType.NEWS_IMAGE2: - view = LayoutInflater.from(parent.getContext()).inflate( - R.layout.news_image2_item, parent, false); + view = mLayoutInflater.inflate(R.layout.news_image2_item, parent, false); return new NewsImage2ViewHolder(view); case ItemViewType.NEWS_IMAGE3: - view = LayoutInflater.from(parent.getContext()).inflate( - R.layout.news_image3_item, parent, false); + view = mLayoutInflater.inflate(R.layout.news_image3_item, parent, false); return new NewsImage3ViewHolder(view); case ItemViewType.LOADING: - view = LayoutInflater.from(parent.getContext()).inflate( - R.layout.refresh_footerview, parent, false); + view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false); return new FooterViewHolder(view); default: return null; @@ -273,7 +268,7 @@ public class News4FragmentAdapter extends BaseRecyclerAdapter { notifyItemChanged(position); // 更新okhttp缓存数据 - VisitManager.updateOkhttpCache(newsEntity.getId()); + VisitManager.updateOkhttpCache(mContext, newsEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCache.java b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCache.java index b44d8babb1..2482c1a0dd 100644 --- a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCache.java +++ b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCache.java @@ -1,9 +1,10 @@ package com.gh.gamecenter.retrofit; -import com.gh.base.AppController; -import com.lightgame.download.FileUtils; +import android.content.Context; + import com.gh.common.util.MD5Utils; import com.gh.common.util.TimestampUtils; +import com.lightgame.download.FileUtils; import java.io.File; import java.io.IOException; @@ -17,12 +18,12 @@ public class OkHttpCache { private static String cachePath; // 根据url获取缓存数据 - public static byte[] getCache(String url) { - if (getCachePath() == null || url == null) { + public static byte[] getCache(Context context, String url) { + if (getCachePath(context) == null || url == null) { return null; } String key = MD5Utils.getUrlMD5(url) + ".1"; - File cacheFile = new File(getCachePath()); + File cacheFile = new File(getCachePath(context)); if (cacheFile.isDirectory()) { for (File file : cacheFile.listFiles()) { if (file.getName().equals(key)) { @@ -33,31 +34,31 @@ public class OkHttpCache { return null; } - public static String getCachePath() { + public static String getCachePath(Context context) { if (cachePath == null) { - File cacheFile = new File(AppController.getInstance().getApplicationContext().getCacheDir(), "okhttp"); + File cacheFile = new File(context.getCacheDir(), "okhttp"); cachePath = cacheFile.getAbsolutePath(); } return cachePath; } // 根据url保存对应的okhttp的缓存 - public static void putCache(String url, byte[] data) { - if (getCachePath() == null || url == null || data == null) { + public static void putCache(Context context, String url, byte[] data) { + if (getCachePath(context) == null || url == null || data == null) { return; } String key = MD5Utils.getUrlMD5(url) + ".1"; - FileUtils.saveFile(new File(getCachePath(), key), data); + FileUtils.saveFile(new File(getCachePath(context), key), data); } // 根据url修改对应的okhttp的缓存 - public static void updateCache(String url, byte[] data) { - if (getCachePath() == null || url == null || data == null) { + public static void updateCache(Context context, String url, byte[] data) { + if (getCachePath(context) == null || url == null || data == null) { return; } try { String key = MD5Utils.getUrlMD5(url) + ".1"; - File file = new File(getCachePath(), key); + File file = new File(getCachePath(context), key); if (file.exists()) { file.createNewFile(); } @@ -65,7 +66,7 @@ public class OkHttpCache { // 如果url包含timestamp,去除timestamp更新缓存 if (url.contains("timestamp")) { url = TimestampUtils.removeTimestamp(url); - updateCache(url, data); + updateCache(context, url, data); } } catch (IOException e) { e.printStackTrace(); diff --git a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpInterceptor.java b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCacheInterceptor.java similarity index 79% rename from app/src/main/java/com/gh/gamecenter/retrofit/OkHttpInterceptor.java rename to app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCacheInterceptor.java index 4b30ddaeaa..b793a37ee5 100644 --- a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpInterceptor.java +++ b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpCacheInterceptor.java @@ -1,6 +1,7 @@ package com.gh.gamecenter.retrofit; -import com.gh.base.AppController; +import android.content.Context; + import com.gh.common.util.GzipUtils; import com.gh.common.util.NetworkUtils; import com.gh.common.util.TimestampUtils; @@ -17,11 +18,21 @@ import okhttp3.ResponseBody; /** * Created by LGT on 2016/11/8. */ -public class OkHttpInterceptor implements Interceptor { +class OkHttpCacheInterceptor implements Interceptor { + + private Context mContext; + + OkHttpCacheInterceptor(Context context) { + mContext = context; + } @Override public Response intercept(Chain chain) throws IOException { +// if (CommonDebug.IS_DEBUG) { +// CommonDebug.logMethodWithParams(this, chain.request().url()); +// } + Request request = chain.request(); // 添加timestamp @@ -31,7 +42,7 @@ public class OkHttpInterceptor implements Interceptor { .build(); // 无网络连接时使用缓存 - if (!NetworkUtils.isNetworkConnected(AppController.getInstance().getApplicationContext())) { + if (!NetworkUtils.isNetworkConnected(mContext)) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build(); @@ -46,7 +57,7 @@ public class OkHttpInterceptor implements Interceptor { // 去除timestamp拿缓存 url = response.request().url().toString(); if (response.code() == 504 && url.contains("timestamp")) { - byte[] data = OkHttpCache.getCache(TimestampUtils.removeTimestamp(url)); + byte[] data = OkHttpCache.getCache(mContext, TimestampUtils.removeTimestamp(url)); if (data != null) { data = GzipUtils.decompressBytes(data); response = response.newBuilder() diff --git a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpNetworkInterceptor.java b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpNetworkInterceptor.java index 37e6b4fdf4..3aac43df6d 100644 --- a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpNetworkInterceptor.java +++ b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpNetworkInterceptor.java @@ -1,6 +1,7 @@ package com.gh.gamecenter.retrofit; -import com.gh.base.AppController; +import android.content.Context; + import com.gh.common.util.GzipUtils; import com.gh.common.util.NetworkUtils; import com.gh.common.util.TimestampUtils; @@ -18,7 +19,7 @@ import okio.BufferedSource; /** * Created by LGT on 2016/11/8. */ -public class OkHttpNetworkInterceptor implements Interceptor { +class OkHttpNetworkInterceptor implements Interceptor { // 空 JSONArray ResponseBody // private static final ResponseBody EMPTY_ARRAY_BODY = ResponseBody.create( @@ -43,9 +44,19 @@ public class OkHttpNetworkInterceptor implements Interceptor { } }; + private final Context mContext; + + OkHttpNetworkInterceptor(Context context) { + mContext = context; + } + @Override public Response intercept(Chain chain) throws IOException { +// if (CommonDebug.IS_DEBUG) { +// CommonDebug.logMethodWithParams(this, chain.request().url()); +// } + Request request = chain.request(); // 添加gzip,默认是添加的 @@ -70,7 +81,7 @@ public class OkHttpNetworkInterceptor implements Interceptor { } // 缓存设置 - if (NetworkUtils.isNetworkConnected(AppController.getInstance().getApplicationContext())) { + if (NetworkUtils.isNetworkConnected(mContext)) { // 有网络时,根据Cache-Control设置 response.newBuilder() .header("Cache-Control", "public, max-age=" + getMaxAge(response.header("Cache-Control"))) @@ -87,8 +98,7 @@ public class OkHttpNetworkInterceptor implements Interceptor { // 如果url包含timestamp,去除timestamp再存一份缓存 String url = response.request().url().toString(); if (response.code() == 200 && url.contains("timestamp")) { - OkHttpCache.putCache(TimestampUtils.removeTimestamp(url), - response.peekBody(Integer.MAX_VALUE - 1).bytes()); + OkHttpCache.putCache(mContext, TimestampUtils.removeTimestamp(url), response.peekBody(Integer.MAX_VALUE - 1).bytes()); } // log 打印 diff --git a/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpRetryInterceptor.kt b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpRetryInterceptor.kt new file mode 100644 index 0000000000..3e3d2cc3c7 --- /dev/null +++ b/app/src/main/java/com/gh/gamecenter/retrofit/OkHttpRetryInterceptor.kt @@ -0,0 +1,55 @@ +package com.gh.gamecenter.retrofit + +import com.lightgame.config.CommonDebug +import okhttp3.Interceptor +import okhttp3.Request +import okhttp3.Response +import java.io.IOException + +/** + * @author CsHeng + * * + * @Date 21/07/2017 + * * + * @Time 3:22 PM + */ +class OkHttpRetryInterceptor internal constructor(private val mMaxRetryCount: Int = 3) : Interceptor { + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + +// if (CommonDebug.IS_DEBUG) { +// CommonDebug.logMethodWithParams(this, chain.request().url()); +// } + + val request = chain.request() + + var response: Response? = doRequest(chain, request) + + var tryCount = 0 + while (response == null && ++tryCount < mMaxRetryCount) { + if (CommonDebug.IS_DEBUG) { + CommonDebug.logMethodWithParams(this, "Retrying ${request.url()} for $tryCount") + } + response = doRequest(chain, request) + } + + // after retries still fail, so we throw IOException as expected + if (response == null) { + throw IOException() + } + + return response + } + + private fun doRequest(chain: Interceptor.Chain, request: Request): Response? { + var response: Response? = null + try { + response = chain.proceed(request) + } catch (e: IOException) { + e.printStackTrace() + } + return response + } + +} diff --git a/app/src/main/java/com/gh/gamecenter/retrofit/RetrofitManager.java b/app/src/main/java/com/gh/gamecenter/retrofit/RetrofitManager.java index 3e5c5f2644..48b5d9e62b 100644 --- a/app/src/main/java/com/gh/gamecenter/retrofit/RetrofitManager.java +++ b/app/src/main/java/com/gh/gamecenter/retrofit/RetrofitManager.java @@ -25,6 +25,7 @@ import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitManager { private static RetrofitManager sInstance; + private static final byte[] LOCK = new byte[0]; private ApiService mApiService; private DataService mDataService; private CommentService mCommentService; @@ -37,7 +38,7 @@ public class RetrofitManager { private RetrofitManager() { mContext = AppController.getInstance().getApplicationContext(); - final Cache cache = new Cache(new File(OkHttpCache.getCachePath()), 10 * 1024 * 1024); // 10Mb + final Cache cache = new Cache(new File(OkHttpCache.getCachePath(mContext)), 10 * 1024 * 1024); // 10Mb final Builder builder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { @@ -48,11 +49,13 @@ public class RetrofitManager { } final OkHttpClient okHttpClient = builder - .addNetworkInterceptor(new OkHttpNetworkInterceptor()) - .addInterceptor(new OkHttpInterceptor()) + .addInterceptor(new OkHttpCacheInterceptor(mContext)) + .addInterceptor(new OkHttpRetryInterceptor()) + .addNetworkInterceptor(new OkHttpNetworkInterceptor(mContext)) .connectTimeout(8, TimeUnit.SECONDS) .cache(cache) .build(); + mApiService = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) @@ -111,16 +114,12 @@ public class RetrofitManager { } public static ApiService getApi() { - return getInstance().getApiService(); - } - - public ApiService getApiService() { - return mApiService; + return getInstance().mApiService; } public static RetrofitManager getInstance() { if (sInstance == null) { - synchronized (RetrofitManager.class) { + synchronized (LOCK) { if (sInstance == null) { sInstance = new RetrofitManager(); } @@ -130,51 +129,27 @@ public class RetrofitManager { } public static DataService getData() { - return getInstance().getDataService(); - } - - public DataService getDataService() { - return mDataService; + return getInstance().mDataService; } public static CommentService getComment() { - return getInstance().getCommentService(); - } - - public CommentService getCommentService() { - return mCommentService; + return getInstance().mCommentService; } public static UserService getUser() { - return getInstance().getUserService(); - } - - public UserService getUserService() { - return mUserService; + return getInstance().mUserService; } public static LibaoService getLibao() { - return getInstance().getLibaoService(); - } - - public LibaoService getLibaoService() { - return mLibaoService; + return getInstance().mLibaoService; } public static MessageService getMessage() { - return getInstance().getMessageService(); - } - - public MessageService getMessageService() { - return mMessageService; + return getInstance().mMessageService; } public static UserseaService getUsersea() { - return getInstance().getUserseaService(); - } - - public UserseaService getUserseaService() { - return mUserseaService; + return getInstance().mUserseaService; } }