Преглед изворни кода

首页首先尝试加载缓存数据

zengjiebin пре 7 година
родитељ
комит
edf4099e80

+ 148 - 22
app/src/main/java/com/kfzs/duanduan/fragment/FgtSmallSheep.java

@@ -35,6 +35,7 @@ import com.kfzs.duanduan.BaseCompatFragment;
 import com.kfzs.duanduan.event.BigEvent;
 import com.kfzs.duanduan.react.ReactUtil;
 import com.kfzs.duanduan.react.SharedPreferences;
+import com.kfzs.duanduan.utils.NumberFormatUtils;
 import com.sheep.gamegroup.di.components.DaggerSmallSheepComponent;
 import com.sheep.gamegroup.di.modules.SmallSheepModule;
 import com.sheep.gamegroup.di.modules.TryMakeMoneyModule;
@@ -85,6 +86,7 @@ import com.sheep.jiuyan.samllsheep.SheepApp;
 import com.sheep.jiuyan.samllsheep.utils.G;
 import com.sunfusheng.marqueeview.MarqueeView;
 
+import org.afinal.simplecache.ApiKey;
 import org.greenrobot.eventbus.EventBus;
 import org.greenrobot.eventbus.Subscribe;
 import org.greenrobot.eventbus.ThreadMode;
@@ -187,7 +189,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
             super.handleMessage(msg);
             switch (msg.what) {
                 case 0:
-                    refalsh();
+                    loadUserInfo();
                     break;
                 case 1:
                     tryMakeMoneyAdp.setIs_succession(3);
@@ -213,6 +215,9 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         TestUtil.testChange(activity, (TextView) getViewById(R.id.test_change));
         TestUtil.testChangeUser(activity, (TextView) getViewById(R.id.test_change_user));
         GlideImageLoader.setImage(bg_newbie_task, "http://cdngame.kuaifazs.com/bg_newbie_task.png");
+        if (pagePresenter != null) {
+            initData();
+        }
     }
 
 
@@ -230,7 +235,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
     }
 
 
-    private void refalsh() {
+    private void loadUserInfo() {
 
         if (myPrice == null || userEntity == null) {
             return;
@@ -294,7 +299,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
             @Override
             public void onRefresh() {
-                initData();
+                refreshData();
                 refresh.setRefreshing(false);
             }
         });
@@ -314,9 +319,127 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
                 }
             }
         });
-        mInitData();
+        initACacheData();
     }
+    private void initACacheData(){
+        if (upview1 != null) {
+            //停止滚动
+            upview1.stopFlipping();
+            upview1.startFlipping();
+        }
+        if (homepageItemNoticeMv != null) {
+            //停止滚动
+            homepageItemNoticeMv.stopFlipping();
+            homepageItemNoticeMv.startFlipping();
+        }
+
+        //用户信息
+        userEntity = CommonUtil.getInstance().getCacheResult(ApiKey.get_info, UserEntity.class);
+        if(userEntity == null){//onResume中从网络获取
+        } else {
+            loadUserInfo();
+        }
+
+        //实时动态
+        List<MoreDataEntity> cacheMoreDataEtyList = CommonUtil.getInstance().getCacheList(ApiKey.award_detail, MoreDataEntity.class);
+        if(ListUtil.isEmpty(cacheMoreDataEtyList)){
+            pagePresenter.getAwardDetail();
+        } else {
+            invite(cacheMoreDataEtyList);
+        }
+        //正在运行的任务
+        position = 0;
+        releaseEtyLists.clear();
+        tryMakeMoneyAdp.clear();
+        tryMakeMoneyAdp.addType(1);
+        for (int i = 0; i < 2; i++) {
+            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
+        }
+        List<TaskAcceptedEty> cacheTaskAcceptedEtyList = CommonUtil.getInstance().getCacheList(ApiKey.new_run_task, TaskAcceptedEty.class);
+        if (ListUtil.isEmpty(cacheTaskAcceptedEtyList)) {//onResume中从网络获取
 
+        } else {
+            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, cacheTaskAcceptedEtyList), position);
+            tryMakeMoneyAdp.addPresenter(tryMakeMoneyPresenter);
+            position++;
+        }
+        List<TaskReleaseEty> cacheTaskReleaseEtyList = CommonUtil.getInstance().getCacheList(ApiKey.release_task, TaskReleaseEty.class);
+        if (ListUtil.isEmpty(cacheTaskReleaseEtyList)) {//onResume中从网络获取
+
+        } else {
+            releaseEtyLists.addAll(cacheTaskReleaseEtyList);
+        }
+
+        tryMakeMoneyAdp.setIs_succession(3);
+        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RELEASE_TASK, releaseEtyLists), position);
+        tryMakeMoneyAdp.notifyDataSetChanged();
+
+        //公告
+        List<BulletinEnty> cacheBulletinEtyList = CommonUtil.getInstance().getCacheList(ApiKey.bulletin, BulletinEnty.class);
+        if(ListUtil.isEmpty(cacheBulletinEtyList)){
+            homepageItemNoticeLayout.setVisibility(View.GONE);
+            pagePresenter.bulletin(null);
+        } else {
+            bulletinEntyLists.clear();
+            bulletinEntyLists.addAll(cacheBulletinEtyList);
+            inviteNotice(bulletinEntyLists);
+        }
+        //轮播
+        List<SlideshowEty> cacheSlideshowEtyList = CommonUtil.getInstance().getCacheList(ApiKey.slideshow, SlideshowEty.class);
+        if(ListUtil.isEmpty(cacheSlideshowEtyList)){
+            homepage_item_banner_layout.setVisibility(View.GONE);
+            pagePresenter.slideshow(null);
+        } else {
+            for (SlideshowEty slideshowEty : cacheSlideshowEtyList) {
+                slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
+                slideshowEtyLists.add(slideshowEty);
+            }
+            bindBanner();
+        }
+        //首页list
+        List<HomeListEntity> cacheHomeListEtyList = CommonUtil.getInstance().getCacheList(ApiKey.home_list, HomeListEntity.class);
+        if(ListUtil.isEmpty(cacheHomeListEtyList)){
+            home_list_gridview_layout.setVisibility(View.GONE);
+            pagePresenter.homeList();//首页list
+        } else {
+            home_list_gridview_layout.setVisibility(View.VISIBLE);
+            homeListEntitys.addAll(cacheHomeListEtyList);
+            boolean isShowQB = false;
+            for (int i = 0; i < homeListEntitys.size(); i++) {
+                if (i < 4) {
+                    homeListEntitysGridview.add(homeListEntitys.get(i));
+                } else {
+                    homeListEntitysListview.add(homeListEntitys.get(i));
+                }
+                if (homeListEntitys.get(i).getJump().equals("6")) {//6Q币充值
+                    isShowQB = !isShowQB;
+                }
+            }
+            SheepApp.getInstance().setShowQB(isShowQB);
+            adpHomeListGrideview.notifyDataSetChanged();
+            adpHomeListListview.notifyDataSetChanged();
+            home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
+        }
+
+        //详情分享地址
+        CommonUtil.getInstance().initUrlConfigByNet(activity);
+        Jump2View.getInstance().tryShowNewbieTask(activity, userEntity, newbie_task);
+    }
+    public void refreshData() {
+        SysAppUtil.checkNet(new Action1<Integer>() {
+            @Override
+            public void call(Integer result) {
+                if (result != 0) {//无网络
+                    if (check_net_ll != null)
+                        check_net_ll.setVisibility(View.VISIBLE);
+                } else {
+                    if (check_net_ll != null)
+                        check_net_ll.setVisibility(View.GONE);
+                }
+            }
+        });
+        mInitData();
+    }
     private void mInitData() {
         if (upview1 != null) {
             //停止滚动
@@ -334,10 +457,9 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
             pagePresenter.getAwardDetail();
         }
 
-        initWechatIsOpen();
         recyclerInitData();//任务
-        pagePresenter.bulletin(null);//轮播
-        pagePresenter.slideshow(null);//公告
+        pagePresenter.bulletin(null);//公告
+        pagePresenter.slideshow(null);//轮播
         pagePresenter.homeList();//首页list
 
         //详情分享地址
@@ -391,11 +513,6 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         tryMakeMoneyPresenter.releaseTask(parameEty);
     }
 
-    /**
-     * 获取微信挂机是否开启状态
-     */
-    private void initWechatIsOpen() {
-    }
 
     @OnClick({R.id.recharge, R.id.withdrawal,
             R.id.newbie_task, R.id.icon_img_iv, R.id.user_layout
@@ -673,10 +790,10 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
     @Override
     public void onResume() {
         super.onResume();
-        if (pagePresenter != null) {
-            initData();
+        if(pagePresenter != null) {
+            pagePresenter.getUserInfo();
+            recyclerInitData();//任务
         }
-
     }
 
     @Override
@@ -741,7 +858,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
     public void onEventMainThread(BigEvent event) {
         switch (event.getEventTypes()) {
             case ONFRESH_FGT_FAMLLSHEEP:
-                initData();
+                refreshData();
                 break;
         }
     }
@@ -752,7 +869,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         UserEntity enity = userEntity;
         enity.setNickname(done.getNikeName());
         userEntity = enity;
-        refalsh();
+        loadUserInfo();
     }
 
     @Subscribe(threadMode = ThreadMode.MAIN)
@@ -761,7 +878,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         enity.setBalance(done.getBalance());
         enity.setTotal_asset(done.getTotal_asset());
         userEntity = enity;
-        refalsh();
+        loadUserInfo();
     }
 
 
@@ -770,7 +887,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         UserEntity enity = userEntity;
         enity.setAvatar(done.getAvatar());
         userEntity = enity;
-        refalsh();
+        loadUserInfo();
     }
 
 
@@ -802,7 +919,7 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
         try {
             userEntity = MyDbManager.getInstance().dbFindUser();
             if (userEntity != null) {
-                refalsh();
+                loadUserInfo();
             }
         } catch (Exception e) {
             e.printStackTrace();
@@ -948,8 +1065,17 @@ public class FgtSmallSheep extends BaseCompatFragment implements SmallSheepContr
      * 点击一条公告
      */
     private void onClickNotice(BulletinEnty item) {
-        //TODO
-        G.showToast(String.format(Locale.CHINA, "您点击了一条公告:%s", JSON.toJSONString(item)));
+        switch (item.getJumpType()){// 跳转类型:11,任务 98,内部h5 99,外部h5
+            case 11:
+                Jump2View.getInstance().goTaskDetailView(activity, NumberFormatUtils.parseInteger(item.getJumpValue()));
+                break;
+            case 98:
+                Jump2View.getInstance().goWeb(activity, item.getJumpValue(), null);
+                break;
+            case 99:
+                Jump2View.getInstance().goWeb(activity, item.getJumpValue());
+                break;
+        }
     }
 
     /**

+ 6 - 2
app/src/main/java/com/sheep/gamegroup/di/modules/NetModule.java

@@ -3,7 +3,10 @@ package com.sheep.gamegroup.di.modules;
 import com.sheep.gamegroup.model.api.ApiService;
 import com.sheep.gamegroup.model.api.StringConverterFactory;
 import com.sheep.gamegroup.model.util.AddPuplicParameIntercept;
+import com.sheep.gamegroup.model.util.CacheInterceptor;
 import com.sheep.gamegroup.model.util.EntityUtils;
+import com.sheep.gamegroup.model.util.LogInterceptor;
+import com.sheep.gamegroup.util.TestUtil;
 import com.sheep.jiuyan.samllsheep.BuildConfig;
 import com.sheep.jiuyan.samllsheep.SheepApp;
 
@@ -28,13 +31,14 @@ public class NetModule {
     @Provides
     @Singleton
     public OkHttpClient provideOkHttpClient() {
-        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
-        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
+        LogInterceptor loggingInterceptor = new LogInterceptor(BuildConfig.XXTEA_ENCRYPT);
+        loggingInterceptor.setLevel(TestUtil.isSheep() ? LogInterceptor.ELevel.NONE : LogInterceptor.ELevel.BODY);
         OkHttpClient okhttpClient = new OkHttpClient.Builder()
                 .connectTimeout(30, TimeUnit.SECONDS)
                 .connectTimeout(20, TimeUnit.SECONDS)
                 .readTimeout(20,TimeUnit.SECONDS)
                 .addInterceptor(new AddPuplicParameIntercept())
+                .addInterceptor(new CacheInterceptor())
                 .addInterceptor(loggingInterceptor)
                 .build();
         return okhttpClient;

+ 0 - 1
app/src/main/java/com/sheep/gamegroup/model/api/BaseMessageConverter.java

@@ -26,7 +26,6 @@ public class BaseMessageConverter implements Converter<ResponseBody, BaseMessage
         String string = value.string();
         String json = decrypt(string);
         BaseMessage baseMessage = JSONObject.parseObject(json, BaseMessage.class);
-        LogUtil.println("sheepApi", "解密", string, baseMessage);
         return baseMessage;
     }
 

+ 36 - 0
app/src/main/java/com/sheep/gamegroup/model/entity/BulletinEnty.java

@@ -3,6 +3,24 @@ package com.sheep.gamegroup.model.entity;
 /**
  * 首页公告
  * Created by ljy on 2018/4/25.
+ * Content:	string
+ 内容
+ CreateTime:	integer ($int64)
+ 创建时间
+ Id:	integer ($int64)
+ IsTiming:	integer ($int64)
+ JumpType:	integer ($int32)
+ 跳转类型:11,任务 98,内部h5 99,外部h5
+ JumpValue:	string
+ 跳转值
+ Order:	integer ($int64)
+ 排序,数字越大越靠前
+ Platform:	integer ($int64)
+ 平台 (1 安卓 2 IOS)
+ ReleaseTime:	integer ($int64)
+ Status:	integer ($int64)
+ UpdateTime:	integer ($int64)
+ 更新时间
  */
 
 public class BulletinEnty {
@@ -11,6 +29,8 @@ public class BulletinEnty {
             private String Id;// 0,
             private int Order;// 0,
             private String UpdateTime;// 0
+            private int JumpType;
+            private String JumpValue;
 
     public String getContent() {
         return Content;
@@ -51,4 +71,20 @@ public class BulletinEnty {
     public void setUpdateTime(String updateTime) {
         UpdateTime = updateTime;
     }
+
+    public int getJumpType() {
+        return JumpType;
+    }
+
+    public void setJumpType(int jumpType) {
+        JumpType = jumpType;
+    }
+
+    public String getJumpValue() {
+        return JumpValue;
+    }
+
+    public void setJumpValue(String jumpValue) {
+        JumpValue = jumpValue;
+    }
 }

+ 0 - 2
app/src/main/java/com/sheep/gamegroup/model/util/AddPuplicParameIntercept.java

@@ -49,7 +49,6 @@ public class AddPuplicParameIntercept implements Interceptor {
                 .newBuilder();
         String method = oldRequest.method();
         RequestBody body = oldRequest.body();
-        LogUtil.println("sheepApi", "request", oldRequest);
         if (BuildConfig.XXTEA_ENCRYPT && (method.equals("POST") || method.equals("PUT"))) {
             RequestBody requestBody = oldRequest.body();
             if (requestBody instanceof FormBody) {
@@ -63,7 +62,6 @@ public class AddPuplicParameIntercept implements Interceptor {
                 }
                 String oldParamsJson = buffer.readUtf8();
                 String newJsonParams = BaseMessageConverter.encrypt(oldParamsJson);
-                LogUtil.println("sheepApi", "加密", oldRequest, oldParamsJson, newJsonParams);
                 if(!TextUtils.isEmpty(newJsonParams))
                     body = RequestBody.create(requestBody.contentType(), newJsonParams);
             }

+ 100 - 0
app/src/main/java/com/sheep/gamegroup/model/util/CacheInterceptor.java

@@ -0,0 +1,100 @@
+package com.sheep.gamegroup.model.util;
+
+import com.sheep.gamegroup.util.LogUtil;
+import com.sheep.jiuyan.samllsheep.SheepApp;
+
+import org.afinal.simplecache.ACache;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.charset.Charset;
+
+import okhttp3.Headers;
+import okhttp3.HttpUrl;
+import okhttp3.Interceptor;
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import okhttp3.internal.http.HttpHeaders;
+import okio.Buffer;
+import okio.BufferedSource;
+
+/**
+ * Created by realicing on 2018/7/20.
+ * realicing@sina.com
+ */
+public class CacheInterceptor implements Interceptor {
+    private static final Charset UTF8 = Charset.forName("UTF-8");
+
+    public Response intercept(Chain chain) throws IOException {
+        Request request = chain.request();
+        String key = request.url().toString().substring((SheepApp.getInstance().getConnectAddress().getAppUrl()+"v1/").length());
+
+        Response response;
+        try {
+            response = chain.proceed(request);
+        } catch (Exception var27) {
+            throw var27;
+        }
+
+        ResponseBody responseBody = response.body();
+        long contentLength = responseBody.contentLength();
+
+        if (HttpHeaders.hasBody(response)) {
+            if (this.bodyHasUnknownEncoding(response.headers())) {
+            } else {
+                BufferedSource source = responseBody.source();
+                source.request(9223372036854775807L);
+                Buffer buffer = source.buffer();
+
+                Charset charset = null;
+                MediaType contentType = responseBody.contentType();
+                if (contentType != null) {
+                    charset = contentType.charset(UTF8);
+                }
+                if (charset == null)
+                    charset = UTF8;
+
+                if (!isPlaintext(buffer)) {
+                    return response;
+                }
+
+                if (contentLength != 0L) {
+                    String result = buffer.clone().readString(charset);
+                    if("GET".equals(request.method())){//缓存get数据
+                        LogUtil.println("sheepLog", "aCache", "key", "=", key);
+                        ACache.get(SheepApp.getInstance()).put(key, result);
+                    }
+                }
+            }
+        }
+
+        return response;
+    }
+
+    static boolean isPlaintext(Buffer buffer) {
+        try {
+            Buffer prefix = new Buffer();
+            long byteCount = buffer.size() < 64L ? buffer.size() : 64L;
+            buffer.copyTo(prefix, 0L, byteCount);
+
+            for (int i = 0; i < 16 && !prefix.exhausted(); ++i) {
+                int codePoint = prefix.readUtf8CodePoint();
+                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
+                    return false;
+                }
+            }
+
+            return true;
+        } catch (EOFException var6) {
+            return false;
+        }
+    }
+
+    private boolean bodyHasUnknownEncoding(Headers headers) {
+        String contentEncoding = headers.get("Content-Encoding");
+        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity") && !contentEncoding.equalsIgnoreCase("gzip");
+    }
+}

+ 265 - 0
app/src/main/java/com/sheep/gamegroup/model/util/LogInterceptor.java

@@ -0,0 +1,265 @@
+package com.sheep.gamegroup.model.util;
+
+import com.sheep.gamegroup.model.api.BaseMessageConverter;
+import com.sheep.gamegroup.util.StringUtils;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import okhttp3.Connection;
+import okhttp3.Headers;
+import okhttp3.Interceptor;
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import okhttp3.internal.http.HttpHeaders;
+import okio.Buffer;
+import okio.BufferedSource;
+import okio.GzipSource;
+
+/**
+ * Created by realicing on 2018/7/20.
+ * realicing@sina.com
+ */
+public class LogInterceptor implements Interceptor {
+    private static final Charset UTF8 = Charset.forName("UTF-8");
+    private final LogInterceptor.ILogger logger;
+    private volatile LogInterceptor.ELevel level;
+    private boolean isDecrypt = false;
+    public LogInterceptor(boolean isDecrypt) {
+        this(isDecrypt, LogInterceptor.ILogger.DEFAULT);
+    }
+
+    public LogInterceptor(boolean isDecrypt, LogInterceptor.ILogger logger) {
+        this.level = LogInterceptor.ELevel.NONE;
+        this.logger = logger;
+        this.isDecrypt = isDecrypt;
+    }
+
+    public LogInterceptor setLevel(LogInterceptor.ELevel level) {
+        if (level == null) {
+            throw new NullPointerException("level == null. Use Level.NONE instead.");
+        } else {
+            this.level = level;
+            return this;
+        }
+    }
+
+    public LogInterceptor.ELevel getLevel() {
+        return this.level;
+    }
+
+    public Response intercept(Chain chain) throws IOException {
+        LogInterceptor.ELevel level = this.level;
+        Request request = chain.request();
+        if (level == LogInterceptor.ELevel.NONE) {
+            return chain.proceed(request);
+        } else {
+            boolean logBody = level == LogInterceptor.ELevel.BODY;
+            boolean logHeaders = logBody || level == LogInterceptor.ELevel.HEADERS;
+            RequestBody requestBody = request.body();
+            boolean hasRequestBody = requestBody != null;
+            Connection connection = chain.connection();
+            String requestStartMessage = "--> " + request.method() + ' ' + request.url() + (connection != null ? " " + connection.protocol() : "");
+            if (!logHeaders && hasRequestBody) {
+                requestStartMessage = requestStartMessage + " (" + requestBody.contentLength() + "-byte body)";
+            }
+
+            this.logger.log(requestStartMessage);
+            if (logHeaders) {
+                if (hasRequestBody) {
+                    if (requestBody.contentType() != null) {
+                        this.logger.log("Content-Type: " + requestBody.contentType());
+                    }
+
+                    if (requestBody.contentLength() != -1L) {
+                        this.logger.log("Content-Length: " + requestBody.contentLength());
+                    }
+                }
+
+                Headers headers = request.headers();
+                int i = 0;
+
+                for(int count = headers.size(); i < count; ++i) {
+                    String name = headers.name(i);
+                    if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
+                        this.logger.log(name + ": " + headers.value(i));
+                    }
+                }
+
+                if (logBody && hasRequestBody) {
+                    if (this.bodyHasUnknownEncoding(request.headers())) {
+                        this.logger.log("--> END " + request.method() + " (encoded body omitted)");
+                    } else {
+                        Buffer buffer = new Buffer();
+                        requestBody.writeTo(buffer);
+                        Charset charset = null;
+                        MediaType contentType = requestBody.contentType();
+                        if (contentType != null) {
+                            charset = contentType.charset(UTF8);
+                        }
+                        if(charset == null)
+                            charset = UTF8;
+
+                        this.logger.log("");
+                        if (isPlaintext(buffer)) {
+                            String result = buffer.readString(charset);
+                            this.logger.log(isDecrypt ? result+"\n"+StringUtils.parseJson(BaseMessageConverter.decrypt(result)) : StringUtils.parseJson(BaseMessageConverter.decrypt(result)));
+                            this.logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
+                        } else {
+                            this.logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
+                        }
+                    }
+                } else {
+                    this.logger.log("--> END " + request.method());
+                }
+            }
+
+            long startNs = System.nanoTime();
+
+            Response response;
+            try {
+                response = chain.proceed(request);
+            } catch (Exception var27) {
+                this.logger.log("<-- HTTP FAILED: " + var27);
+                throw var27;
+            }
+
+            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
+            ResponseBody responseBody = response.body();
+            long contentLength = responseBody.contentLength();
+            String bodySize = contentLength != -1L ? contentLength + "-byte" : "unknown-length";
+            this.logger.log("<-- " + response.code() + (response.message().isEmpty() ? "" : ' ' + response.message()) + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
+            if (logHeaders) {
+                Headers headers = response.headers();
+                int i = 0;
+
+                for(int count = headers.size(); i < count; ++i) {
+                    this.logger.log(headers.name(i) + ": " + headers.value(i));
+                }
+
+                if (logBody && HttpHeaders.hasBody(response)) {
+                    if (this.bodyHasUnknownEncoding(response.headers())) {
+                        this.logger.log("<-- END HTTP (encoded body omitted)");
+                    } else {
+                        BufferedSource source = responseBody.source();
+                        source.request(9223372036854775807L);
+                        Buffer buffer = source.buffer();
+                        Long gzippedLength = null;
+                        if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
+                            gzippedLength = buffer.size();
+                            GzipSource gzippedResponseBody = null;
+
+                            try {
+                                gzippedResponseBody = new GzipSource(buffer.clone());
+                                buffer = new Buffer();
+                                buffer.writeAll(gzippedResponseBody);
+                            } finally {
+                                if (gzippedResponseBody != null) {
+                                    gzippedResponseBody.close();
+                                }
+
+                            }
+                        }
+
+                        Charset charset = null;
+                        MediaType contentType = responseBody.contentType();
+                        if (contentType != null) {
+                            charset = contentType.charset(UTF8);
+                        }
+                        if(charset == null)
+                            charset = UTF8;
+
+                        if (!isPlaintext(buffer)) {
+                            this.logger.log("");
+                            this.logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
+                            return response;
+                        }
+
+                        if (contentLength != 0L) {
+                            this.logger.log("");
+                            String result = buffer.clone().readString(charset);
+                            this.logger.log(isDecrypt ? result+"\n"+StringUtils.parseJson(BaseMessageConverter.decrypt(result)) : StringUtils.parseJson(BaseMessageConverter.decrypt(result)));
+                        }
+
+                        if (gzippedLength != null) {
+                            this.logger.log("<-- END HTTP (" + buffer.size() + "-byte, " + gzippedLength + "-gzipped-byte body)");
+                        } else {
+                            this.logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
+                        }
+                    }
+                } else {
+                    this.logger.log("<-- END HTTP");
+                }
+            }
+
+            return response;
+        }
+    }
+
+    static boolean isPlaintext(Buffer buffer) {
+        try {
+            Buffer prefix = new Buffer();
+            long byteCount = buffer.size() < 64L ? buffer.size() : 64L;
+            buffer.copyTo(prefix, 0L, byteCount);
+
+            for(int i = 0; i < 16 && !prefix.exhausted(); ++i) {
+                int codePoint = prefix.readUtf8CodePoint();
+                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
+                    return false;
+                }
+            }
+
+            return true;
+        } catch (EOFException var6) {
+            return false;
+        }
+    }
+
+    private boolean bodyHasUnknownEncoding(Headers headers) {
+        String contentEncoding = headers.get("Content-Encoding");
+        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity") && !contentEncoding.equalsIgnoreCase("gzip");
+    }
+
+    //规定每段显示的长度
+    private static int LOG_MAXLENGTH = 2000;
+    public interface ILogger {
+        LogInterceptor.ILogger DEFAULT = new LogInterceptor.ILogger() {
+            public void log(String message) {
+
+                int strLength = message.length();
+                int start = 0;
+                int end = LOG_MAXLENGTH;
+                for (int i = 0; i < 100; i++) {
+                    //剩下的文本还是大于规定长度则继续重复截取并输出
+                    if (strLength > end) {
+                        Logger.getLogger("sheepLog").log(Level.INFO, message.substring(start, end), (Throwable) null);
+                        start = end;
+                        end = end + LOG_MAXLENGTH;
+                    } else {
+                        Logger.getLogger("sheepLog").log(Level.INFO, message.substring(start, strLength), (Throwable) null);
+                        break;
+                    }
+                }
+            }
+        };
+
+        void log(String var1);
+    }
+
+    public static enum ELevel {
+        NONE,
+        BASIC,
+        HEADERS,
+        BODY;
+
+        private ELevel() {
+        }
+    }
+}

+ 1 - 1
app/src/main/java/com/sheep/gamegroup/model/util/SheepSubscriber.java

@@ -82,7 +82,7 @@ public abstract class SheepSubscriber<T> extends Subscriber<T> {
 
                 if(baseMessage.getCode() == 0)
                     baseMessage.setCode(throwable.code);
-                LogUtil.println("sheepApi", "onError", e.getMessage(), throwable.message, baseMessage);
+//                LogUtil.println("sheepApi", "onError", e.getMessage(), throwable.message, baseMessage);
                 onError(baseMessage);
             }else {
                 BaseMessage baseMessage = new BaseMessage();

+ 12 - 12
app/src/main/java/com/sheep/gamegroup/presenter/SmallSheepPresenter.java

@@ -116,22 +116,22 @@ public class SmallSheepPresenter implements SmallSheepContract.Persenter {
                     }
                 });
     }
-
+    private SheepSubscriber<BaseMessage> bulletinSs = new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
+        @Override
+        public void onError(BaseMessage baseMessage) {
+            view.failbulletin(baseMessage);
+        }
+
+        @Override
+        public void onNext(BaseMessage baseMessage) {
+            view.successbulletin(baseMessage);
+        }
+    };
     @Override
     public void bulletin(Object o) {
         apiService.bulletin(1,10)
                 .subscribeOn(Schedulers.io())
                 .observeOn(AndroidSchedulers.mainThread())
-                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
-                    @Override
-                    public void onError(BaseMessage baseMessage) {
-                        view.failbulletin(baseMessage);
-                    }
-
-                    @Override
-                    public void onNext(BaseMessage baseMessage) {
-                        view.successbulletin(baseMessage);
-                    }
-                });
+                .subscribe(bulletinSs);
     }
 }

+ 30 - 0
app/src/main/java/com/sheep/gamegroup/util/CommonUtil.java

@@ -28,6 +28,7 @@ import com.kfzs.duanduan.event.BigEvent;
 import com.kfzs.duanduan.event.EventTypes;
 import com.sheep.gamegroup.absBase.BaseActivity;
 import com.sheep.gamegroup.alipay.PayResult;
+import com.sheep.gamegroup.model.api.BaseMessageConverter;
 import com.sheep.gamegroup.model.entity.BaseMessage;
 import com.sheep.gamegroup.model.entity.DialogConfig;
 import com.sheep.gamegroup.model.entity.GameAccountEntity;
@@ -47,6 +48,7 @@ import com.sheep.gamegroup.model.util.SheepSubscriber;
 import com.sheep.gamegroup.presenter.TryMakeMoneyPresenter;
 import com.sheep.gamegroup.usage.AppUsageManager;
 import com.sheep.gamegroup.view.activity.GameTaskOrderListAct;
+import com.sheep.jiuyan.samllsheep.BuildConfig;
 import com.sheep.jiuyan.samllsheep.R;
 import com.sheep.jiuyan.samllsheep.SheepApp;
 import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
@@ -1371,4 +1373,32 @@ public class CommonUtil {
         }
         return false;
     }
+
+    private ACache aCache;
+    public <T> T getCacheResult(String key, Class<T> classT) {
+        if(aCache == null){
+            aCache = ACache.get(SheepApp.getInstance());
+        }
+        String cacheData = aCache.getAsString(key);
+        if(!TextUtils.isEmpty(cacheData)){
+            if(BuildConfig.XXTEA_ENCRYPT){
+                cacheData = BaseMessageConverter.decrypt(cacheData);
+            }
+            return JSON.parseObject(cacheData, BaseMessage.class).getData(classT);
+        }
+        return null;
+    }
+    public <T> List<T> getCacheList(String key, Class<T> classT) {
+        if(aCache == null){
+            aCache = ACache.get(SheepApp.getInstance());
+        }
+        String cacheData = aCache.getAsString(key);
+        if(!TextUtils.isEmpty(cacheData)){
+            if(BuildConfig.XXTEA_ENCRYPT){
+                cacheData = BaseMessageConverter.decrypt(cacheData);
+            }
+            return JSON.parseObject(cacheData, BaseMessage.class).getDataList(classT);
+        }
+        return null;
+    }
 }

+ 0 - 3
app/src/main/java/com/sheep/gamegroup/util/Jump2View.java

@@ -827,9 +827,6 @@ public class Jump2View {
      * @param title
      */
     public void goWeb(Context context, String url, String title){
-        goCardWeb(context, url, title, null);
-    }
-    public void goCardWeb(Context context, String url, String title, String id){
         if(TextUtils.isEmpty(url)){
             G.showToast(R.string.service_data_error);
             return;

+ 26 - 0
app/src/main/java/com/sheep/gamegroup/util/StringUtils.java

@@ -7,6 +7,10 @@ import android.text.TextUtils;
 
 import com.sheep.jiuyan.samllsheep.SheepApp;
 
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
@@ -259,4 +263,26 @@ public class StringUtils {
         return matcher.matches();
     }
 
+    /**
+     * 格式化json
+     * @param msg
+     * @return
+     */
+    public static String parseJson(String msg){
+        String message;
+        try {
+            if (msg.startsWith("{")) {
+                JSONObject jsonObject = new JSONObject(msg);
+                message = jsonObject.toString(4);//最重要的方法,就一行,返回格式化的json字符串,其中的数字4是缩进字符数
+            } else if (msg.startsWith("[")) {
+                JSONArray jsonArray = new JSONArray(msg);
+                message = jsonArray.toString(4);
+            } else {
+                message = msg;
+            }
+        } catch (JSONException e) {
+            message = msg;
+        }
+        return message;
+    }
 }

+ 39 - 0
app/src/main/java/org/afinal/simplecache/ApiKey.java

@@ -0,0 +1,39 @@
+package org.afinal.simplecache;
+
+/**
+ * Created by realicing on 2018/7/23.
+ * realicing@sina.com
+ * 07-23 11:59:21.130 7444-7517/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/version/new_version?type=0
+ 07-23 11:59:21.524 7444-7517/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/advertising/advertisements?type=1
+ 07-23 11:59:23.512 7444-7517/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/user/get_info/
+ 07-23 11:59:23.660 7444-7548/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/user/check_label
+ 07-23 11:59:23.813 7444-7517/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/version/new_version?type=0
+ 07-23 11:59:24.053 7444-7648/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/user/get_info/
+ 07-23 11:59:24.056 7444-7653/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/slideshow?platform=1
+ 07-23 11:59:24.056 7444-7651/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/bulletin?page=1&per_page=10
+ 07-23 11:59:24.070 7444-7657/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/url/
+ 07-23 11:59:24.077 7444-7649/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/user/award_detail?page=0&per_page=100
+ 07-23 11:59:24.081 7444-7658/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/find/articles_tags/list
+ 07-23 11:59:24.084 7444-7656/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/home_list
+ 07-23 11:59:24.092 7444-7650/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/release_task?page=1&per_page=100&platform=1&is_hot=1&is_recommend=0&about_to_begin=0&task_type=-1&is_succession=3
+ 07-23 11:59:24.095 7444-7547/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/advertising/advertisements?type=2
+ 07-23 11:59:24.329 7444-7653/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/find/applications/downloads/status
+ 07-23 11:59:24.371 7444-7547/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/accepted_task/new_run_task/?is_succession=3
+ 07-23 11:59:24.634 7444-7651/com.sheep.jiuyan.samllsheep I/System.out: sheepLog aCache key = app/find/articles/list?page=1&per_page=100&tag_id=0
+ */
+public class ApiKey {
+    //公告
+    public static final String bulletin = "app/bulletin?page=1&per_page=10";
+    //轮播
+    public static final String slideshow = "app/slideshow?platform=1";
+    //home_list
+    public static final String home_list = "app/home_list";
+    //用户信息
+    public static final String get_info = "app/user/get_info/";
+    //award_detail
+    public static final String award_detail = "app/user/award_detail?page=0&per_page=100";
+    //首页获取所有发布的热门任务(试玩任务、游戏任务、连续任务)
+    public static final String release_task = "app/release_task?page=1&per_page=100&platform=1&is_hot=1&is_recommend=0&about_to_begin=0&task_type=-1&is_succession=3";
+    //首页获取正在运行的任务(试玩任务、游戏任务、连续任务)
+    public static final String new_run_task = "app/accepted_task/new_run_task/?is_succession=3";
+}

+ 2 - 2
app/src/main/res/layout/homepage_item_top2.xml

@@ -24,7 +24,7 @@
         android:id="@+id/name_tv"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/app_name"
+        android:text="@string/loading"
         android:textColor="@color/txt_white"
         android:textSize="15sp"
         android:layout_marginBottom="12dp"
@@ -49,7 +49,7 @@
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginBottom="1dp"
-        android:text="@string/app_name"
+        android:text="@string/loading"
         android:textColor="@color/txt_white"
         android:textSize="18sp"
         app:layout_constraintBottom_toBottomOf="parent"

+ 1 - 0
app/src/main/res/values/str_network_strings.xml

@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <string name="coming_soon">敬请期待</string>
+    <string name="loading">加载中</string>
     <string name="loading_data">数据正在加载中,请稍候重试</string>
     <string name="service_data_error">数据配置中,请稍候再试</string>
     <string name="unknown_error">未知错误,请稍候再试</string>