From 7e169eb46205b364a0bdf29c737664f9a44e57a3 Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Mon, 21 Sep 2026 16:51:49 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E7=BD=91?= =?UTF-8?q?=E7=BB=9C=E5=8E=BB=E9=87=8D=E4=B8=8E=E9=94=81=E5=B1=8F=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 移除 ConnectManager,改由 RepeatRequestInterceptor 在请求前拦截重复请求并复用真实响应; MyAppList 改用缓存控制刷新;PushManager 去除短节流限制; ManagerService 引入本地 pwdUnlocked 标记,避免密码解锁直接改写服务端锁屏镜像, 并修复浮窗隐藏后状态未复位导致的 NPE。 --- app/build.gradle | 4 +- .../com/fuying/sn/base/BaseApplication.java | 2 - .../com/fuying/sn/manager/ConnectManager.java | 143 -------- .../sn/network/NetInterfaceManager.java | 24 +- .../interceptor/RepeatRequestInterceptor.java | 327 +++++++++++++++--- .../java/com/fuying/sn/push/PushManager.java | 72 ++-- .../com/fuying/sn/service/ManagerService.java | 59 +++- 7 files changed, 363 insertions(+), 268 deletions(-) delete mode 100644 app/src/main/java/com/fuying/sn/manager/ConnectManager.java diff --git a/app/build.gradle b/app/build.gradle index 7571533..4125f3d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -69,8 +69,8 @@ android { official { flavorDimensions "default" - versionCode 102 - versionName "3.6.1" + versionCode 103 + versionName "3.6.2" applicationId "com.fuying.sn" buildConfigField "String", "ROOT_URL", '"https://as.fuyingy.com/android/"' diff --git a/app/src/main/java/com/fuying/sn/base/BaseApplication.java b/app/src/main/java/com/fuying/sn/base/BaseApplication.java index 4f24ddf..a8fa11a 100644 --- a/app/src/main/java/com/fuying/sn/base/BaseApplication.java +++ b/app/src/main/java/com/fuying/sn/base/BaseApplication.java @@ -20,7 +20,6 @@ import com.fuying.sn.BuildConfig; import com.fuying.sn.desktop.RunningAppManager; import com.fuying.sn.desktop.TimeControlManager; import com.fuying.sn.manager.AmapManager; -import com.fuying.sn.manager.ConnectManager; import com.fuying.sn.manager.ControlManager; import com.fuying.sn.manager.DeviceManager; import com.fuying.sn.manager.time.TimeManager; @@ -96,7 +95,6 @@ public class BaseApplication extends Application { CrashReport.setDeviceId(this, Utils.getSerial()); LogDBManager.init(this); - ConnectManager.init(this); Aria.init(this); Aria.download(this).resumeAllTask(); NetInterfaceManager.init(this); diff --git a/app/src/main/java/com/fuying/sn/manager/ConnectManager.java b/app/src/main/java/com/fuying/sn/manager/ConnectManager.java deleted file mode 100644 index 80ae011..0000000 --- a/app/src/main/java/com/fuying/sn/manager/ConnectManager.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.fuying.sn.manager; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.util.Log; - -import com.fuying.sn.config.CommonConfig; -import com.tencent.mmkv.MMKV; - -public class ConnectManager { - private static final String TAG = "ConnectManager"; - - - public static final long ONE_SECOND_TIME = 1000; - public static final long ONE_MINUTES_TIME = 60 * ONE_SECOND_TIME; - public static final long FIFTEEN_MINUTES_TIME = ONE_MINUTES_TIME * 15; - public static final long HALF_HOUR_TIME = FIFTEEN_MINUTES_TIME * 2; - public static final long ONE_HOUR_TIME = HALF_HOUR_TIME * 2; - public static final long SIX_HOUR_TIME = ONE_HOUR_TIME * 6; - public static final long HALF_DAY_TIME = SIX_HOUR_TIME * 2; - public static final long ONE_DAY_TIME = HALF_DAY_TIME * 2; - - /*重启后连接成功的时间*/ - public static final String REBOOT_LAST_ONNECT_TIME = "reboot_last_connect_time"; - /*WiFi连接后连接成功的时间*/ - public static final String WIFI_LAST_CONNECT_TIME = "WiFi_last_connect_time"; - /*打开设备信息连接成功的时间*/ - public static final String OPENINFO_LAST_ONNECT_TIME = "opneinfo_last_connect_time"; - - - @SuppressLint("StaticFieldLeak") - private static ConnectManager sInstance; - private Context mContext; - private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE); - - private ConnectManager(Context context) { - if (context == null) { - throw new RuntimeException("Context is NULL"); - } - this.mContext = context; - - } - - public static void init(Context context) { - if (sInstance == null) { - Log.e(TAG, "init: "); - sInstance = new ConnectManager(context); - } - } - - public static ConnectManager getInstance() { - if (sInstance == null) { - throw new IllegalStateException("You must be init ConnectManager first"); - } - return sInstance; - } - - public long getConnectModeTime(ConnectMode connectMode) { - long time = 0; - switch (connectMode) { - case DEFAULT: - time = 0; - break; - case ONE_MINUTE: - time = ONE_MINUTES_TIME; - break; - case FIFTEEN_MINUTES: - time = FIFTEEN_MINUTES_TIME; - break; - case HALF_HOUR: - time = HALF_HOUR_TIME; - break; - case ONE_HOUR: - time = ONE_HOUR_TIME; - break; - case SIX_HOUR: - time = SIX_HOUR_TIME; - break; - case HALF_DAY: - time = HALF_DAY_TIME; - break; - case ONE_DAY: - time = ONE_DAY_TIME; - break; - default: - } - return time; - } - - public boolean isNeedConnect(String key, ConnectMode connectMode) { - long nowTime = System.currentTimeMillis(); - long lastTime = mMMKV.decodeLong(key, 0); - long intervalTime = getConnectModeTime(connectMode); - //防止一分钟内重复请求 - return nowTime - lastTime > intervalTime && nowTime - lastTime > ONE_SECOND_TIME; - } - - /** - * 请求成功后记录本次连接时间,供 {@link #isNeedConnect(String, ConnectMode)} 做节流判断。 - * 注意:原实现从未写入该时间戳,导致节流机制形同虚设,这里补齐。 - */ - public void updateConnectTime(String key) { - mMMKV.encode(key, System.currentTimeMillis()); - } - - - /** - * @return 重启后是否连接 - */ - public boolean isRebootFistConnect() { - long rebootTime = mMMKV.decodeLong(REBOOT_LAST_ONNECT_TIME, 0); - //只在开机后15内连接,其他情况为service重启 - long time = System.currentTimeMillis() - rebootTime; - return time < 15 * 1000; - } - - /** - * @return 今天WiFi连接是否有连接 - */ -// public boolean isWiFiFistConnect() { -// long time = mMMKV.decodeLong(WIFI_LAST_CONNECT_TIME, 0); -// return !TimeUtils.isTodayTime(time); -// } - - /** - * @return 今天打开设备信息后是否连接 - */ -// public boolean isOpenInfoFistConnect() { -// long time = mMMKV.decodeLong(OPENINFO_LAST_ONNECT_TIME, 0); -// return !TimeUtils.isTodayTime(time); -// } - - /** - * @param WiFiAlias - * @return 今天切换WiFi后是否连接 - */ -// public boolean isWiFiCutoverFistConnect(String WiFiAlias) { -// long time = mMMKV.decodeLong(WiFiAlias, 0); -// return !TimeUtils.isTodayTime(time); -// } - - -} diff --git a/app/src/main/java/com/fuying/sn/network/NetInterfaceManager.java b/app/src/main/java/com/fuying/sn/network/NetInterfaceManager.java index 698ee0d..fabc6f8 100644 --- a/app/src/main/java/com/fuying/sn/network/NetInterfaceManager.java +++ b/app/src/main/java/com/fuying/sn/network/NetInterfaceManager.java @@ -53,7 +53,6 @@ import com.fuying.sn.desktop.RunningAppManager; import com.fuying.sn.desktop.TimeControlManager; import com.fuying.sn.disklrucache.CacheHelper; import com.fuying.sn.gson.GsonUtils; -import com.fuying.sn.manager.ConnectManager; import com.fuying.sn.manager.ConnectMode; import com.fuying.sn.manager.ControlManager; import com.fuying.sn.manager.time.TimeConfigRepository; @@ -526,7 +525,9 @@ public class NetInterfaceManager { } public Observable>> getMyAppListObservable() { - return schedule(getAppApi().getMyAppList(Utils.getSerial())); + return withCache(schedule(getAppApi().getMyAppList(Utils.getSerial())), + UrlAddress.GET_MY_APP_LIST, + CACHE_EXPIRE_ONE_MINUTE * 60); } public Observable>> getAppJumpObservable() { @@ -2728,23 +2729,8 @@ public class NetInterfaceManager { } public void getMyAppList(MyAppListCallback callback) { - if (ConnectManager.getInstance().isNeedConnect(UrlAddress.GET_MY_APP_LIST, ConnectMode.SIX_HOUR)) { - getMyAppListObservable() - .subscribe(getMyAppListObservable(callback)); - } else { - String jsonString = mCacheHelper.getAsString(UrlAddress.GET_MY_APP_LIST); - //为 "" 是已经请求成功的 - if (jsonString == null) { - getMyAppListObservable() - .subscribe(getMyAppListObservable(callback)); - } else { - Gson gson = new Gson(); - Type type = new TypeToken>() { - }.getType(); - List myAppUsageBeans = gson.fromJson(jsonString, type); - callback.setMyAppList(myAppUsageBeans); - } - } + getMyAppListObservable() + .subscribe(getMyAppListObservable(callback)); } public Observer>> getMyAppListObservable(MyAppListCallback callback) { diff --git a/app/src/main/java/com/fuying/sn/network/interceptor/RepeatRequestInterceptor.java b/app/src/main/java/com/fuying/sn/network/interceptor/RepeatRequestInterceptor.java index 9a9c257..f40c8b9 100644 --- a/app/src/main/java/com/fuying/sn/network/interceptor/RepeatRequestInterceptor.java +++ b/app/src/main/java/com/fuying/sn/network/interceptor/RepeatRequestInterceptor.java @@ -8,9 +8,13 @@ import com.fuying.sn.utils.MD5Util; import org.jetbrains.annotations.NotNull; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import okhttp3.Headers; import okhttp3.Interceptor; +import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; @@ -19,89 +23,308 @@ import okhttp3.ResponseBody; import okio.Buffer; /** - * v1.0 2022-07-15 16:16:52 + * 重复请求拦截器。 + * + *

原实现是在 {@code chain.proceed()} 之后才判断是否为重复请求,此时请求早已发到服务器, + * 只能丢弃返回结果,所以服务端依然会收到两次(甚至多次)请求;并且记录在 finally 中立即删除, + * 去重窗口几乎为零,重复请求根本拦不住。

+ * + *

优化后的策略:

+ *
    + *
  • 发请求之前先判断是否已经有相同请求:有则等待它的结果并复用,不再访问服务器;
  • + *
  • 请求完成后在 {@link #REUSE_WINDOW_MS} 内保留结果,短时间内相同的请求直接复用结果;
  • + *
  • 复用时使用真实的状态码、响应头和响应体,调用方无感知(原来的空 {@link Response} 会让 + * 解析层直接抛异常);
  • + *
  • 无响应体或响应体过大(超过 {@link #MAX_DEDUP_BODY_BYTES})的请求不参与去重,直接透传, + * 避免占用大量内存。
  • + *
+ * + *

v1.0 2022-07-15 16:16:52

*/ public class RepeatRequestInterceptor implements Interceptor { private static final String TAG = "RepeatRequestInterceptor"; - private final ConcurrentHashMap requestIdsMap = new ConcurrentHashMap<>(); - public static final String REPEAT_REQUEST_PROTOCOL = "OKHTTP_REPEAT_REQUEST_PROTOCOL"; + /** + * 等待进行中请求返回结果的最长时间,超时后本次请求自己访问服务器。 + * 需要大于 OkHttpClient 的超时时间(当前为 5 秒)。 + */ + private static final long WAIT_IN_FLIGHT_TIMEOUT_MS = 10_000L; + + /** + * 请求完成后结果保留的时间。在该时间内收到相同请求,直接复用结果,不再访问服务器。 + * 需要小于业务侧的刷新间隔(ConnectMode 最小为 1 分钟)。 + */ + private static final long REUSE_WINDOW_MS = 500L; + + /** + * 超过该大小的响应体不参与去重(直接透传),避免内存占用 + */ + private static final long MAX_DEDUP_BODY_BYTES = 1024 * 1024L; + + /** + * 参与去重 key 计算的请求体最大字节数 + */ + private static final int MAX_BODY_BYTES_FOR_KEY = 8 * 1024; + + /** + * 日志中请求体、响应体的最大长度 + */ + private static final int MAX_LOG_BODY_LENGTH = 10240; + + private final ConcurrentHashMap recordMap = new ConcurrentHashMap<>(); @NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Request request = chain.request(); - Response response = chain.proceed(request); - ResponseBody responseBody = response.body(); + String bodyText = requestBodyToString(request.body()); + String requestKey = buildRequestKey(request, bodyText); - //会消费请求,导致请求多次 - String content = responseBody.string(); -// Response copy = response.newBuilder().body(responseBody).build(); - ResponseBody copy = ResponseBody.create(responseBody.contentType(), content); - if (BuildConfig.DEBUG) { -// Log.e(TAG, "请求体返回:| Response: " + request.url() + "\t body: " + content); + clearExpiredRecords(); + + RepeatRecord record = acquireRecord(requestKey); + if (record == null) { + // 已有相同请求,但没有拿到可用结果(上一次失败、超时或结果过大),本次请求直接访问服务器 + return chain.proceed(request); } - //相同的请求 - String requestKey = MD5Util.getUpperMD5Str(request.method() + request.url().toString() + requestBodyToString(request.body())); - long time = System.currentTimeMillis();//请求时间 + if (!record.isOwner()) { + // 复用相同请求的结果:服务端只会收到一次请求 + log("复用请求:", requestKey, request, bodyText); + return record.newResponse(request); + } + + log("注册请求:", requestKey, request, bodyText); try { - if (requestIdsMap.size() > 0 && requestIdsMap.containsKey(requestKey)) { - log("重复请求:", requestKey, request); - //下面这行写了不会抛出onerror -// chain.call().cancel(); - return new Response.Builder() - .protocol(Protocol.get(REPEAT_REQUEST_PROTOCOL)) - .request(request) //multi thread - .build(); + Response response = chain.proceed(request); + ResponseBody responseBody = response.body(); + if (responseBody == null || responseBody.contentLength() > MAX_DEDUP_BODY_BYTES) { + // 无响应体或响应体过大:不消费 body,也不参与去重,直接透传 + logResponse(request, null); + return response; } - requestIdsMap.put(requestKey, time); - log("注册请求:", requestKey, request); -// RepeatRequestInterceptor.Builder builder = request.newBuilder(); -// builder.addHeader("header", jsonObject.toString()); - return response.newBuilder().body(copy).build(); + + // body 只能被消费一次,读出来之后重建一个新的 body 返回给调用方 + MediaType contentType = responseBody.contentType(); + byte[] bytes = responseBody.bytes(); + logResponse(request, bytes); + if (bytes.length <= MAX_DEDUP_BODY_BYTES) { + // 缓存结果,供等待中的、以及短时间内后续的相同请求复用 + record.complete(response, bytes, contentType); + } + return response.newBuilder().body(ResponseBody.create(contentType, bytes)).build(); } catch (IOException e) { Log.e(TAG, "intercept: " + e.getMessage()); throw e; } finally { - if (requestIdsMap.containsKey(requestKey) && requestIdsMap.containsValue(time)) {//请求任务完成删除map中的数据 - requestIdsMap.remove(requestKey); - log("移除请求:", requestKey, request); + // 兜底:无论成功、失败还是异常,都结束记录,避免等待中的相同请求被一直阻塞 + record.finish(); + } + } + + /** + * 获取请求对应的去重记录。 + * + * @return 返回记录表示本次请求要么成为 owner 去访问服务器、要么直接复用已有结果; + * 返回 null 表示已有相同请求但结果不可用,本次请求自己访问服务器(不参与去重) + */ + private RepeatRecord acquireRecord(String requestKey) { + while (true) { + long now = System.currentTimeMillis(); + RepeatRecord record = recordMap.get(requestKey); + if (record == null) { + RepeatRecord created = new RepeatRecord(); + if (recordMap.putIfAbsent(requestKey, created) == null) { + created.markOwner(); + return created; + } + continue;// 其他线程抢先注册,重新判断 + } + if (record.isExpired(now)) { + // 结果已过期,替换为本次请求的记录并成为 owner + RepeatRecord created = new RepeatRecord(); + if (recordMap.replace(requestKey, record, created)) { + created.markOwner(); + return created; + } + continue; + } + // 已有相同请求:等待它的结果,拿到结果直接复用 + if (record.await(WAIT_IN_FLIGHT_TIMEOUT_MS)) { + return record; + } + return null; + } + } + + /** + * 清理过期记录,释放其缓存的响应体 + */ + private void clearExpiredRecords() { + if (recordMap.isEmpty()) { + return; + } + long now = System.currentTimeMillis(); + for (Map.Entry entry : recordMap.entrySet()) { + RepeatRecord record = entry.getValue(); + if (record.isExpired(now)) { + recordMap.remove(entry.getKey(), record); } } } - private void log(String action, String requestKey, Request request) { + private static String buildRequestKey(Request request, String bodyText) { + return MD5Util.getUpperMD5Str(request.method() + "|" + request.url() + "|" + bodyText); + } + + /** + * 请求体转字符串,用于计算去重 key 和输出日志。 + * 只读取可重复读写的请求体,避免把一次性(one-shot)请求体读空。 + */ + private static String requestBodyToString(RequestBody body) { + if (body == null || body.isOneShot()) { + return ""; + } + try { + Buffer buffer = new Buffer(); + body.writeTo(buffer); + long size = buffer.size(); + if (size > MAX_BODY_BYTES_FOR_KEY) { + // 请求体过大时只取前一部分参与去重,避免不必要的内存开销 + return size + ":" + buffer.readByteString(MAX_BODY_BYTES_FOR_KEY).hex(); + } + return buffer.readUtf8(); + } catch (Exception e) { + return ""; + } + } + + private static void log(String action, String requestKey, Request request, String bodyText) { if (BuildConfig.DEBUG) { - Log.e("REPEAT-REQUEST", action + requestKey + " Method @" + request.method() + " --- " + " URL = " + request.url() + "\t" + bodyToString(request)); + String body = bodyText.length() > MAX_LOG_BODY_LENGTH ? "-too long" : bodyText; + Log.e("REPEAT-REQUEST", action + requestKey + " Method @" + request.method() + + " --- " + " URL = " + request.url().encodedPath() + "\t" + body); } else { Log.e("REPEAT-REQUEST", action + requestKey + " Method @" + request.method()); } } - private static String bodyToString(final Request request) { - try { - final Request copy = request.newBuilder().build(); - final Buffer buffer = new Buffer(); - copy.body().writeTo(buffer); - if (buffer.size() > 4096) { - return "-too long"; - } - return buffer.readUtf8(); - } catch (Exception e) { - return "-"; + private static void logResponse(Request request, byte[] bytes) { + if (!BuildConfig.DEBUG) { + return; + } + if (bytes == null || bytes.length > MAX_LOG_BODY_LENGTH) { + Log.e(TAG, "请求体返回:| Response: " + request.url() + "\t body: too long"); + } else { + Log.e(TAG, "请求体返回:| Response: " + request.url() + + "\t body: " + new String(bytes, StandardCharsets.UTF_8)); } } - private static String requestBodyToString(RequestBody body) { - try { - final Buffer buffer = new Buffer(); - body.writeTo(buffer); - if (buffer.size() > 4096) { - return "-too long"; + /** + * 一次请求的去重记录:owner 线程负责访问服务器,其他相同请求等待并复用它的结果 + */ + private static final class RepeatRecord { + private final Object lock = new Object(); + private final long createdTime = System.currentTimeMillis(); + + private boolean owner; + private boolean finished; + private boolean succeed; + private long finishedTime; + private byte[] body; + private MediaType contentType; + private Headers headers; + private Protocol protocol; + private int code; + private String message; + + void markOwner() { + owner = true; + } + + boolean isOwner() { + return owner; + } + + /** + * 等待 owner 请求结束 + * + * @return true 表示已拿到可复用的结果 + */ + boolean await(long timeoutMs) { + synchronized (lock) { + if (!finished) { + try { + lock.wait(timeoutMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return finished && succeed; + } + } + + /** + * 请求成功,缓存结果并唤醒等待的请求 + */ + void complete(Response response, byte[] body, MediaType contentType) { + synchronized (lock) { + if (finished) { + return; + } + this.body = body; + this.contentType = contentType; + this.headers = response.headers(); + this.protocol = response.protocol(); + this.code = response.code(); + this.message = response.message(); + this.succeed = true; + finished = true; + finishedTime = System.currentTimeMillis(); + lock.notifyAll(); + } + } + + /** + * 请求结束(失败或异常时没有可复用的结果);重复调用忽略 + */ + void finish() { + synchronized (lock) { + if (finished) { + return; + } + finished = true; + finishedTime = System.currentTimeMillis(); + lock.notifyAll(); + } + } + + /** + * 进行中的记录超过等待超时时间、已完成的记录超过结果保留时间即视为过期 + */ + boolean isExpired(long now) { + synchronized (lock) { + if (!finished) { + return now - createdTime > WAIT_IN_FLIGHT_TIMEOUT_MS; + } + return now - finishedTime > REUSE_WINDOW_MS; + } + } + + /** + * 用缓存的结果构建响应,状态码、响应头、响应体都是真实数据 + */ + Response newResponse(Request request) { + synchronized (lock) { + return new Response.Builder() + .request(request) + .protocol(protocol) + .code(code) + .message(message) + .headers(headers) + .body(ResponseBody.create(contentType, body)) + .build(); } - return buffer.readUtf8(); - } catch (Exception e) { - return "-"; } } } diff --git a/app/src/main/java/com/fuying/sn/push/PushManager.java b/app/src/main/java/com/fuying/sn/push/PushManager.java index ffec3e4..f2b81c4 100644 --- a/app/src/main/java/com/fuying/sn/push/PushManager.java +++ b/app/src/main/java/com/fuying/sn/push/PushManager.java @@ -1,5 +1,7 @@ package com.fuying.sn.push; +import static com.fuying.sn.service.ManagerService.LOCK_STATE; + import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.content.ComponentName; @@ -28,8 +30,6 @@ import com.fuying.sn.dialog.CustomDialog; import com.fuying.sn.disklrucache.CacheHelper; import com.fuying.sn.gson.GsonUtils; import com.fuying.sn.manager.ControlManager; -import com.fuying.sn.manager.ConnectManager; -import com.fuying.sn.manager.ConnectMode; import com.fuying.sn.manager.DeviceManager; import com.fuying.sn.manager.time.TimeManager; import com.fuying.sn.network.NetInterfaceManager; @@ -77,8 +77,6 @@ import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; -import static com.fuying.sn.service.ManagerService.LOCK_STATE; - public class PushManager { private static final String TAG = "PushManager"; @@ -101,7 +99,7 @@ public class PushManager { * 定时轮询兜底间隔:推送不可靠时,靠它保证最终能拿到最新配置。 * 15 分钟一次,配合下方短节流,不会频繁请求接口。 */ - private static final long POLLING_INTERVAL = ConnectManager.FIFTEEN_MINUTES_TIME; + private static final long POLLING_INTERVAL = 15 * 60 * 1000L; /** * 推送防抖窗口:短时间内连续多条推送,合并为一次刷新。 */ @@ -597,7 +595,7 @@ public class PushManager { } private void updateUserSettings() { - Log.e(TAG, "updateUserSettings: " ); + Log.e(TAG, "updateUserSettings: "); NetInterfaceManager.removeCache(UrlAddress.SN_INFO); NetInterfaceManager.removeCache(UrlAddress.GET_SETTINGS); NetInterfaceManager.removeCache(UrlAddress.SN_TIME_CONTROL); @@ -611,8 +609,6 @@ public class PushManager { // NetInterfaceManager.getInstance().getMachineTimeControl(); // NetInterfaceManager.getInstance().getSnTimeControl(); TimeManager.getInstance().getTimeControl(); - // 记录本次刷新时间,供短节流判断 - ConnectManager.getInstance().updateConnectTime(KEY_PUSH_REFRESH); } }, 2345); } @@ -663,12 +659,8 @@ public class PushManager { mDebounceRunnable = new Runnable() { @Override public void run() { - if (ConnectManager.getInstance().isNeedConnect(KEY_PUSH_REFRESH, ConnectMode.ONE_MINUTE)) { - Log.e(TAG, "scheduleRefresh -> updateUserSettings"); - updateUserSettings(); - } else { - Log.e(TAG, "scheduleRefresh skipped (throttled)"); - } + Log.e(TAG, "scheduleRefresh -> updateUserSettings"); + updateUserSettings(); } }; } @@ -686,12 +678,8 @@ public class PushManager { mSyncHandler.post(new Runnable() { @Override public void run() { - if (ConnectManager.getInstance().isNeedConnect(KEY_PUSH_REFRESH, ConnectMode.ONE_MINUTE)) { - Log.e(TAG, "triggerRefresh -> updateUserSettings"); - updateUserSettings(); - } else { - Log.e(TAG, "triggerRefresh skipped (throttled)"); - } + Log.e(TAG, "triggerRefresh -> updateUserSettings"); + updateUserSettings(); } }); } @@ -1192,13 +1180,13 @@ public class PushManager { private static Observable getScreenshot(String filePath) { Observable screenshotObservable = Observable.create(new ObservableOnSubscribe() { - @Override - public void subscribe(ObservableEmitter e) { - int code = CmdUtil.execute("screencap -p " + filePath).code; - e.onNext(code); - e.onComplete(); - } - }).subscribeOn(Schedulers.io()) + @Override + public void subscribe(ObservableEmitter e) { + int code = CmdUtil.execute("screencap -p " + filePath).code; + e.onNext(code); + e.onComplete(); + } + }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); return screenshotObservable; } @@ -1215,15 +1203,15 @@ public class PushManager { String path = context.getExternalFilesDir("db").getAbsolutePath(); String filePath = path + File.separator + Utils.getSerial() + ".png"; getScreenshot(filePath).concatMap(new Function>() { - @Override - public ObservableSource apply(Integer integer) throws Exception { - if (integer != 0) { - throw new FileNotFoundException(); - } - File file = new File(filePath); - if (!file.exists()) { - throw new FileNotFoundException(filePath); - } + @Override + public ObservableSource apply(Integer integer) throws Exception { + if (integer != 0) { + throw new FileNotFoundException(); + } + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } // Bitmap bitmap = BitmapFactory.decodeFile(filePath); // if (bitmap.getWidth() < bitmap.getHeight()) { // bitmap = ImageUtils.rotate(bitmap, -90, bitmap.getWidth(), bitmap.getHeight()); @@ -1239,12 +1227,12 @@ public class PushManager { // fos.write(b, 0, x); // } // fos.close(); - MediaType mediaType = MediaType.Companion.parse("image/png"); - RequestBody requestBody = RequestBody.Companion.create(file, mediaType); - MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody); - return getSendFile(filePath, body); - } - }).subscribeOn(Schedulers.io()) + MediaType mediaType = MediaType.Companion.parse("image/png"); + RequestBody requestBody = RequestBody.Companion.create(file, mediaType); + MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody); + return getSendFile(filePath, body); + } + }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override diff --git a/app/src/main/java/com/fuying/sn/service/ManagerService.java b/app/src/main/java/com/fuying/sn/service/ManagerService.java index 2cae013..174f9a1 100644 --- a/app/src/main/java/com/fuying/sn/service/ManagerService.java +++ b/app/src/main/java/com/fuying/sn/service/ManagerService.java @@ -67,6 +67,13 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta private boolean screenlocked = false; private boolean timelocked = false; + /** + * 本地"已用密码解除锁屏"标记。 + * 密码解锁不再直接改写服务端锁屏状态镜像(LOCK_STATE),改用本标记表达本地放行; + * 服务端下发新状态(推送/轮询)或进程重启后该标记失效。 + */ + private boolean pwdUnlocked = false; + @Override public void onDisconnected() { @@ -174,6 +181,8 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta if (code == 200) { JsonObject jsonObject = GsonUtils.getJsonObject(GsonUtils.toJSONString(baseResponse.data)); int is_screen_lock = jsonObject.get("is_screen_lock").getAsInt(); + // 服务端状态已下发,本地"密码解锁"标记失效 + pwdUnlocked = false; setLockedState(is_screen_lock); } else { if (!timelocked) { @@ -214,6 +223,18 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta public static final String LOCK_STATE = "SCRENN_LOOCKED_STATE"; + /** + * 读取本地当前应生效的服务端锁屏状态。 + * LOCK_STATE(SP) 是服务端下发状态的镜像,密码解锁只置内存标记 pwdUnlocked, + * 在服务端下发新状态之前不再从镜像里恢复锁屏。 + */ + private int getServerLockState() { + if (pwdUnlocked) { + return 0; + } + return (int) SPUtils.get(ManagerService.this, LOCK_STATE, 0); + } + private void showFloatingWindow(String name) { // if (BuildConfig.DEBUG) { // Log.e(TAG, "showFloatingWindow: debug mode skip"); @@ -352,7 +373,14 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta private void hide() { hideFloatingWindow(); - SPUtils.put(ManagerService.this, ManagerService.LOCK_STATE, 0); + // 视图已移除,内存状态必须同步复位: + // 否则下一次 setFloatingWindow() 会走到 screenlocked==true 分支去访问已置空的 topView, + // 抛出 NPE(release 包被全局异常捕获吞掉),表现为锁屏浮窗再也不出现。 + screenlocked = false; + timelocked = false; + // 密码解锁改用内存标记表达,不再在这里把 LOCK_STATE 直接清 0; + // 该 key 交给"按服务端状态落地"的路径(setLockedState / 推送 / 轮询)统一维护。 + pwdUnlocked = true; NetInterfaceManager.getInstance().getUpdateLockScreenObservable() .subscribe(new Observer() { @Override @@ -419,11 +447,15 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta if (ACTION_LOCK.equals(action)) { // String name = intent.getStringExtra("name"); String name = "屏幕已锁定"; + // 服务端状态已下发,本地"密码解锁"标记失效 + pwdUnlocked = false; if (!timelocked) { showFloatingWindow(name); } screenlocked = true; } else if (ACTION_UNLOCK.equals(action)) { + // 服务端状态已下发,本地"密码解锁"标记失效 + pwdUnlocked = false; if (!timelocked) { hideFloatingWindow(); } @@ -455,6 +487,9 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta String action = intent.getAction(); if (Intent.ACTION_DATE_CHANGED.equals(action)) { Log.e(TAG, "TimeChangedReceiver:" + "data changed"); + // 跨天后"工作日/周末"规则集会切换,立即按新日期重算, + // 避免浮窗/锁屏状态延迟到下一次 TIME_TICK 才生效 + setFloatingWindow(); } else if (Intent.ACTION_TIME_CHANGED.equals(action)) { Log.e(TAG, "TimeChangedReceiver:" + "time changed"); } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { @@ -480,22 +515,30 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta TimeUtils.ContralTime workingContralTime = TimeUtils.getWorkingDayContralTime(ManagerService.this); TimeUtils.ContralTime weekContralTime = TimeUtils.getWeekDayContralTime(ManagerService.this); // if (null != workingContralTime) { - if (TimeUtils.inContralTime(workingContralTime, weekContralTime)) { - if (!screenlocked) { - showFloatingWindow("可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this)); + // 先算出本轮的时间管控状态并落到 timelocked,再处理 UI/锁屏状态: + // setLockedState() 与 LockScreenReceiver 内部都要判断 timelocked, + // 若在调用之后才赋值,会出现"服务端锁屏已下发但不显示"的空窗(最长到下一次 TIME_TICK)。 + boolean inTimeControl = TimeUtils.inContralTime(workingContralTime, weekContralTime); + timelocked = inTimeControl; + String timeText = "可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this); + if (inTimeControl) { + if (null == topView) { + // topView 可能已被 hideFloatingWindow()(密码解锁、解锁广播)移除, + // 此时不能再对 topView 取子控件,否则 NPE 会导致浮窗再也不显示。 + showFloatingWindow(timeText); } else { TextView textView = topView.findViewById(R.id.textView); - textView.setText("可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this)); + if (null != textView) { + textView.setText(timeText); + } } - timelocked = true; } else { // getScreenLockState(); - int is_screen_lock = (int) SPUtils.get(ManagerService.this, LOCK_STATE, 0); + int is_screen_lock = getServerLockState(); setLockedState(is_screen_lock); if (!screenlocked) { hideFloatingWindow(); } - timelocked = false; } // } else { // if (!screenlocked) {