refactor: 重构网络去重与锁屏状态管理

移除 ConnectManager,改由 RepeatRequestInterceptor 在请求前拦截重复请求并复用真实响应;
MyAppList 改用缓存控制刷新;PushManager 去除短节流限制;
ManagerService 引入本地 pwdUnlocked 标记,避免密码解锁直接改写服务端锁屏镜像,
并修复浮窗隐藏后状态未复位导致的 NPE。
This commit is contained in:
tongtong committed 2026-09-21 16:51:49 +08:00
1 parent d28f9ac288
commit 7e169eb462
7 files changed
+363 -268

No files matched your search

+2 -2
View File
@@ -69,8 +69,8 @@ android {
official { official {
flavorDimensions "default" flavorDimensions "default"
versionCode 102 versionCode 103
versionName "3.6.1" versionName "3.6.2"
applicationId "com.fuying.sn" applicationId "com.fuying.sn"
buildConfigField "String", "ROOT_URL", '"https://as.fuyingy.com/android/"' buildConfigField "String", "ROOT_URL", '"https://as.fuyingy.com/android/"'
@@ -20,7 +20,6 @@ import com.fuying.sn.BuildConfig;
import com.fuying.sn.desktop.RunningAppManager; import com.fuying.sn.desktop.RunningAppManager;
import com.fuying.sn.desktop.TimeControlManager; import com.fuying.sn.desktop.TimeControlManager;
import com.fuying.sn.manager.AmapManager; import com.fuying.sn.manager.AmapManager;
import com.fuying.sn.manager.ConnectManager;
import com.fuying.sn.manager.ControlManager; import com.fuying.sn.manager.ControlManager;
import com.fuying.sn.manager.DeviceManager; import com.fuying.sn.manager.DeviceManager;
import com.fuying.sn.manager.time.TimeManager; import com.fuying.sn.manager.time.TimeManager;
@@ -96,7 +95,6 @@ public class BaseApplication extends Application {
CrashReport.setDeviceId(this, Utils.getSerial()); CrashReport.setDeviceId(this, Utils.getSerial());
LogDBManager.init(this); LogDBManager.init(this);
ConnectManager.init(this);
Aria.init(this); Aria.init(this);
Aria.download(this).resumeAllTask(); Aria.download(this).resumeAllTask();
NetInterfaceManager.init(this); NetInterfaceManager.init(this);
@@ -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);
// }
}
@@ -53,7 +53,6 @@ import com.fuying.sn.desktop.RunningAppManager;
import com.fuying.sn.desktop.TimeControlManager; import com.fuying.sn.desktop.TimeControlManager;
import com.fuying.sn.disklrucache.CacheHelper; import com.fuying.sn.disklrucache.CacheHelper;
import com.fuying.sn.gson.GsonUtils; import com.fuying.sn.gson.GsonUtils;
import com.fuying.sn.manager.ConnectManager;
import com.fuying.sn.manager.ConnectMode; import com.fuying.sn.manager.ConnectMode;
import com.fuying.sn.manager.ControlManager; import com.fuying.sn.manager.ControlManager;
import com.fuying.sn.manager.time.TimeConfigRepository; import com.fuying.sn.manager.time.TimeConfigRepository;
@@ -526,7 +525,9 @@ public class NetInterfaceManager {
} }
public Observable<BaseResponse<List<MyAppUsageBean>>> getMyAppListObservable() { public Observable<BaseResponse<List<MyAppUsageBean>>> 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<BaseResponse<List<AppJump>>> getAppJumpObservable() { public Observable<BaseResponse<List<AppJump>>> getAppJumpObservable() {
@@ -2728,23 +2729,8 @@ public class NetInterfaceManager {
} }
public void getMyAppList(MyAppListCallback callback) { public void getMyAppList(MyAppListCallback callback) {
if (ConnectManager.getInstance().isNeedConnect(UrlAddress.GET_MY_APP_LIST, ConnectMode.SIX_HOUR)) { getMyAppListObservable()
getMyAppListObservable() .subscribe(getMyAppListObservable(callback));
.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<List<MyAppUsageBean>>() {
}.getType();
List<MyAppUsageBean> myAppUsageBeans = gson.fromJson(jsonString, type);
callback.setMyAppList(myAppUsageBeans);
}
}
} }
public Observer<BaseResponse<List<MyAppUsageBean>>> getMyAppListObservable(MyAppListCallback callback) { public Observer<BaseResponse<List<MyAppUsageBean>>> getMyAppListObservable(MyAppListCallback callback) {
@@ -8,9 +8,13 @@ import com.fuying.sn.utils.MD5Util;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import okhttp3.Headers;
import okhttp3.Interceptor; import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol; import okhttp3.Protocol;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
@@ -19,89 +23,308 @@ import okhttp3.ResponseBody;
import okio.Buffer; import okio.Buffer;
/** /**
* v1.0 2022-07-15 16:16:52 * 重复请求拦截器。
*
* <p>原实现是在 {@code chain.proceed()} 之后才判断是否为重复请求,此时请求早已发到服务器,
* 只能丢弃返回结果,所以服务端依然会收到两次(甚至多次)请求;并且记录在 finally 中立即删除,
* 去重窗口几乎为零,重复请求根本拦不住。</p>
*
* <p>优化后的策略:</p>
* <ul>
* <li>发请求之前先判断是否已经有相同请求:有则等待它的结果并复用,不再访问服务器;</li>
* <li>请求完成后在 {@link #REUSE_WINDOW_MS} 内保留结果,短时间内相同的请求直接复用结果;</li>
* <li>复用时使用真实的状态码、响应头和响应体,调用方无感知(原来的空 {@link Response} 会让
* 解析层直接抛异常);</li>
* <li>无响应体或响应体过大(超过 {@link #MAX_DEDUP_BODY_BYTES})的请求不参与去重,直接透传,
* 避免占用大量内存。</li>
* </ul>
*
* <p>v1.0 2022-07-15 16:16:52</p>
*/ */
public class RepeatRequestInterceptor implements Interceptor { public class RepeatRequestInterceptor implements Interceptor {
private static final String TAG = "RepeatRequestInterceptor"; private static final String TAG = "RepeatRequestInterceptor";
private final ConcurrentHashMap<String, Long> 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<String, RepeatRecord> recordMap = new ConcurrentHashMap<>();
@NotNull @NotNull
@Override @Override
public Response intercept(@NotNull Chain chain) throws IOException { public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request(); Request request = chain.request();
Response response = chain.proceed(request); String bodyText = requestBodyToString(request.body());
ResponseBody responseBody = response.body(); String requestKey = buildRequestKey(request, bodyText);
//会消费请求,导致请求多次 clearExpiredRecords();
String content = responseBody.string();
// Response copy = response.newBuilder().body(responseBody).build(); RepeatRecord record = acquireRecord(requestKey);
ResponseBody copy = ResponseBody.create(responseBody.contentType(), content); if (record == null) {
if (BuildConfig.DEBUG) { // 已有相同请求,但没有拿到可用结果(上一次失败、超时或结果过大),本次请求直接访问服务器
// Log.e(TAG, "请求体返回:| Response: " + request.url() + "\t body: " + content); return chain.proceed(request);
} }
//相同的请求 if (!record.isOwner()) {
String requestKey = MD5Util.getUpperMD5Str(request.method() + request.url().toString() + requestBodyToString(request.body())); // 复用相同请求的结果:服务端只会收到一次请求
long time = System.currentTimeMillis();//请求时间 log("复用请求:", requestKey, request, bodyText);
return record.newResponse(request);
}
log("注册请求:", requestKey, request, bodyText);
try { try {
if (requestIdsMap.size() > 0 && requestIdsMap.containsKey(requestKey)) { Response response = chain.proceed(request);
log("重复请求:", requestKey, request); ResponseBody responseBody = response.body();
//下面这行写了不会抛出onerror if (responseBody == null || responseBody.contentLength() > MAX_DEDUP_BODY_BYTES) {
// chain.call().cancel(); // 无响应体或响应体过大:不消费 body,也不参与去重,直接透传
return new Response.Builder() logResponse(request, null);
.protocol(Protocol.get(REPEAT_REQUEST_PROTOCOL)) return response;
.request(request) //multi thread
.build();
} }
requestIdsMap.put(requestKey, time);
log("注册请求:", requestKey, request); // body 只能被消费一次,读出来之后重建一个新的 body 返回给调用方
// RepeatRequestInterceptor.Builder builder = request.newBuilder(); MediaType contentType = responseBody.contentType();
// builder.addHeader("header", jsonObject.toString()); byte[] bytes = responseBody.bytes();
return response.newBuilder().body(copy).build(); 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) { } catch (IOException e) {
Log.e(TAG, "intercept: " + e.getMessage()); Log.e(TAG, "intercept: " + e.getMessage());
throw e; throw e;
} finally { } finally {
if (requestIdsMap.containsKey(requestKey) && requestIdsMap.containsValue(time)) {//请求任务完成删除map中的数据 // 兜底:无论成功、失败还是异常,都结束记录,避免等待中的相同请求被一直阻塞
requestIdsMap.remove(requestKey); record.finish();
log("移除请求:", requestKey, request); }
}
/**
* 获取请求对应的去重记录。
*
* @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<String, RepeatRecord> 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) { 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 { } else {
Log.e("REPEAT-REQUEST", action + requestKey + " Method @" + request.method()); Log.e("REPEAT-REQUEST", action + requestKey + " Method @" + request.method());
} }
} }
private static String bodyToString(final Request request) { private static void logResponse(Request request, byte[] bytes) {
try { if (!BuildConfig.DEBUG) {
final Request copy = request.newBuilder().build(); return;
final Buffer buffer = new Buffer(); }
copy.body().writeTo(buffer); if (bytes == null || bytes.length > MAX_LOG_BODY_LENGTH) {
if (buffer.size() > 4096) { Log.e(TAG, "请求体返回:| Response: " + request.url() + "\t body: too long");
return "-too long"; } else {
} Log.e(TAG, "请求体返回:| Response: " + request.url()
return buffer.readUtf8(); + "\t body: " + new String(bytes, StandardCharsets.UTF_8));
} catch (Exception e) {
return "-";
} }
} }
private static String requestBodyToString(RequestBody body) { /**
try { * 一次请求的去重记录:owner 线程负责访问服务器,其他相同请求等待并复用它的结果
final Buffer buffer = new Buffer(); */
body.writeTo(buffer); private static final class RepeatRecord {
if (buffer.size() > 4096) { private final Object lock = new Object();
return "-too long"; 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 "-";
} }
} }
} }
@@ -1,5 +1,7 @@
package com.fuying.sn.push; package com.fuying.sn.push;
import static com.fuying.sn.service.ManagerService.LOCK_STATE;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName; import android.content.ComponentName;
@@ -28,8 +30,6 @@ import com.fuying.sn.dialog.CustomDialog;
import com.fuying.sn.disklrucache.CacheHelper; import com.fuying.sn.disklrucache.CacheHelper;
import com.fuying.sn.gson.GsonUtils; import com.fuying.sn.gson.GsonUtils;
import com.fuying.sn.manager.ControlManager; 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.DeviceManager;
import com.fuying.sn.manager.time.TimeManager; import com.fuying.sn.manager.time.TimeManager;
import com.fuying.sn.network.NetInterfaceManager; import com.fuying.sn.network.NetInterfaceManager;
@@ -77,8 +77,6 @@ import okhttp3.MediaType;
import okhttp3.MultipartBody; import okhttp3.MultipartBody;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import static com.fuying.sn.service.ManagerService.LOCK_STATE;
public class PushManager { public class PushManager {
private static final String TAG = "PushManager"; private static final String TAG = "PushManager";
@@ -101,7 +99,7 @@ public class PushManager {
* 定时轮询兜底间隔:推送不可靠时,靠它保证最终能拿到最新配置。 * 定时轮询兜底间隔:推送不可靠时,靠它保证最终能拿到最新配置。
* 15 分钟一次,配合下方短节流,不会频繁请求接口。 * 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() { private void updateUserSettings() {
Log.e(TAG, "updateUserSettings: " ); Log.e(TAG, "updateUserSettings: ");
NetInterfaceManager.removeCache(UrlAddress.SN_INFO); NetInterfaceManager.removeCache(UrlAddress.SN_INFO);
NetInterfaceManager.removeCache(UrlAddress.GET_SETTINGS); NetInterfaceManager.removeCache(UrlAddress.GET_SETTINGS);
NetInterfaceManager.removeCache(UrlAddress.SN_TIME_CONTROL); NetInterfaceManager.removeCache(UrlAddress.SN_TIME_CONTROL);
@@ -611,8 +609,6 @@ public class PushManager {
// NetInterfaceManager.getInstance().getMachineTimeControl(); // NetInterfaceManager.getInstance().getMachineTimeControl();
// NetInterfaceManager.getInstance().getSnTimeControl(); // NetInterfaceManager.getInstance().getSnTimeControl();
TimeManager.getInstance().getTimeControl(); TimeManager.getInstance().getTimeControl();
// 记录本次刷新时间,供短节流判断
ConnectManager.getInstance().updateConnectTime(KEY_PUSH_REFRESH);
} }
}, 2345); }, 2345);
} }
@@ -663,12 +659,8 @@ public class PushManager {
mDebounceRunnable = new Runnable() { mDebounceRunnable = new Runnable() {
@Override @Override
public void run() { public void run() {
if (ConnectManager.getInstance().isNeedConnect(KEY_PUSH_REFRESH, ConnectMode.ONE_MINUTE)) { Log.e(TAG, "scheduleRefresh -> updateUserSettings");
Log.e(TAG, "scheduleRefresh -> updateUserSettings"); updateUserSettings();
updateUserSettings();
} else {
Log.e(TAG, "scheduleRefresh skipped (throttled)");
}
} }
}; };
} }
@@ -686,12 +678,8 @@ public class PushManager {
mSyncHandler.post(new Runnable() { mSyncHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
if (ConnectManager.getInstance().isNeedConnect(KEY_PUSH_REFRESH, ConnectMode.ONE_MINUTE)) { Log.e(TAG, "triggerRefresh -> updateUserSettings");
Log.e(TAG, "triggerRefresh -> updateUserSettings"); updateUserSettings();
updateUserSettings();
} else {
Log.e(TAG, "triggerRefresh skipped (throttled)");
}
} }
}); });
} }
@@ -1192,13 +1180,13 @@ public class PushManager {
private static Observable<Integer> getScreenshot(String filePath) { private static Observable<Integer> getScreenshot(String filePath) {
Observable<Integer> screenshotObservable = Observable.create(new ObservableOnSubscribe<Integer>() { Observable<Integer> screenshotObservable = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override @Override
public void subscribe(ObservableEmitter<Integer> e) { public void subscribe(ObservableEmitter<Integer> e) {
int code = CmdUtil.execute("screencap -p " + filePath).code; int code = CmdUtil.execute("screencap -p " + filePath).code;
e.onNext(code); e.onNext(code);
e.onComplete(); e.onComplete();
} }
}).subscribeOn(Schedulers.io()) }).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()); .observeOn(AndroidSchedulers.mainThread());
return screenshotObservable; return screenshotObservable;
} }
@@ -1215,15 +1203,15 @@ public class PushManager {
String path = context.getExternalFilesDir("db").getAbsolutePath(); String path = context.getExternalFilesDir("db").getAbsolutePath();
String filePath = path + File.separator + Utils.getSerial() + ".png"; String filePath = path + File.separator + Utils.getSerial() + ".png";
getScreenshot(filePath).concatMap(new Function<Integer, ObservableSource<BaseResponse>>() { getScreenshot(filePath).concatMap(new Function<Integer, ObservableSource<BaseResponse>>() {
@Override @Override
public ObservableSource<BaseResponse> apply(Integer integer) throws Exception { public ObservableSource<BaseResponse> apply(Integer integer) throws Exception {
if (integer != 0) { if (integer != 0) {
throw new FileNotFoundException(); throw new FileNotFoundException();
} }
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
throw new FileNotFoundException(filePath); throw new FileNotFoundException(filePath);
} }
// Bitmap bitmap = BitmapFactory.decodeFile(filePath); // Bitmap bitmap = BitmapFactory.decodeFile(filePath);
// if (bitmap.getWidth() < bitmap.getHeight()) { // if (bitmap.getWidth() < bitmap.getHeight()) {
// bitmap = ImageUtils.rotate(bitmap, -90, 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.write(b, 0, x);
// } // }
// fos.close(); // fos.close();
MediaType mediaType = MediaType.Companion.parse("image/png"); MediaType mediaType = MediaType.Companion.parse("image/png");
RequestBody requestBody = RequestBody.Companion.create(file, mediaType); RequestBody requestBody = RequestBody.Companion.create(file, mediaType);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody); MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
return getSendFile(filePath, body); return getSendFile(filePath, body);
} }
}).subscribeOn(Schedulers.io()) }).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseResponse>() { .subscribe(new Observer<BaseResponse>() {
@Override @Override
@@ -67,6 +67,13 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
private boolean screenlocked = false; private boolean screenlocked = false;
private boolean timelocked = false; private boolean timelocked = false;
/**
* 本地"已用密码解除锁屏"标记。
* 密码解锁不再直接改写服务端锁屏状态镜像(LOCK_STATE),改用本标记表达本地放行;
* 服务端下发新状态(推送/轮询)或进程重启后该标记失效。
*/
private boolean pwdUnlocked = false;
@Override @Override
public void onDisconnected() { public void onDisconnected() {
@@ -174,6 +181,8 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
if (code == 200) { if (code == 200) {
JsonObject jsonObject = GsonUtils.getJsonObject(GsonUtils.toJSONString(baseResponse.data)); JsonObject jsonObject = GsonUtils.getJsonObject(GsonUtils.toJSONString(baseResponse.data));
int is_screen_lock = jsonObject.get("is_screen_lock").getAsInt(); int is_screen_lock = jsonObject.get("is_screen_lock").getAsInt();
// 服务端状态已下发,本地"密码解锁"标记失效
pwdUnlocked = false;
setLockedState(is_screen_lock); setLockedState(is_screen_lock);
} else { } else {
if (!timelocked) { if (!timelocked) {
@@ -214,6 +223,18 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
public static final String LOCK_STATE = "SCRENN_LOOCKED_STATE"; 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) { private void showFloatingWindow(String name) {
// if (BuildConfig.DEBUG) { // if (BuildConfig.DEBUG) {
// Log.e(TAG, "showFloatingWindow: debug mode skip"); // Log.e(TAG, "showFloatingWindow: debug mode skip");
@@ -352,7 +373,14 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
private void hide() { private void hide() {
hideFloatingWindow(); 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() NetInterfaceManager.getInstance().getUpdateLockScreenObservable()
.subscribe(new Observer<BaseResponse>() { .subscribe(new Observer<BaseResponse>() {
@Override @Override
@@ -419,11 +447,15 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
if (ACTION_LOCK.equals(action)) { if (ACTION_LOCK.equals(action)) {
// String name = intent.getStringExtra("name"); // String name = intent.getStringExtra("name");
String name = "屏幕已锁定"; String name = "屏幕已锁定";
// 服务端状态已下发,本地"密码解锁"标记失效
pwdUnlocked = false;
if (!timelocked) { if (!timelocked) {
showFloatingWindow(name); showFloatingWindow(name);
} }
screenlocked = true; screenlocked = true;
} else if (ACTION_UNLOCK.equals(action)) { } else if (ACTION_UNLOCK.equals(action)) {
// 服务端状态已下发,本地"密码解锁"标记失效
pwdUnlocked = false;
if (!timelocked) { if (!timelocked) {
hideFloatingWindow(); hideFloatingWindow();
} }
@@ -455,6 +487,9 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
String action = intent.getAction(); String action = intent.getAction();
if (Intent.ACTION_DATE_CHANGED.equals(action)) { if (Intent.ACTION_DATE_CHANGED.equals(action)) {
Log.e(TAG, "TimeChangedReceiver:" + "data changed"); Log.e(TAG, "TimeChangedReceiver:" + "data changed");
// 跨天后"工作日/周末"规则集会切换,立即按新日期重算,
// 避免浮窗/锁屏状态延迟到下一次 TIME_TICK 才生效
setFloatingWindow();
} else if (Intent.ACTION_TIME_CHANGED.equals(action)) { } else if (Intent.ACTION_TIME_CHANGED.equals(action)) {
Log.e(TAG, "TimeChangedReceiver:" + "time changed"); Log.e(TAG, "TimeChangedReceiver:" + "time changed");
} else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { } 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 workingContralTime = TimeUtils.getWorkingDayContralTime(ManagerService.this);
TimeUtils.ContralTime weekContralTime = TimeUtils.getWeekDayContralTime(ManagerService.this); TimeUtils.ContralTime weekContralTime = TimeUtils.getWeekDayContralTime(ManagerService.this);
// if (null != workingContralTime) { // if (null != workingContralTime) {
if (TimeUtils.inContralTime(workingContralTime, weekContralTime)) { // 先算出本轮的时间管控状态并落到 timelocked,再处理 UI/锁屏状态:
if (!screenlocked) { // setLockedState() 与 LockScreenReceiver 内部都要判断 timelocked,
showFloatingWindow("可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this)); // 若在调用之后才赋值,会出现"服务端锁屏已下发但不显示"的空窗(最长到下一次 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 { } else {
TextView textView = topView.findViewById(R.id.textView); TextView textView = topView.findViewById(R.id.textView);
textView.setText("可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this)); if (null != textView) {
textView.setText(timeText);
}
} }
timelocked = true;
} else { } else {
// getScreenLockState(); // getScreenLockState();
int is_screen_lock = (int) SPUtils.get(ManagerService.this, LOCK_STATE, 0); int is_screen_lock = getServerLockState();
setLockedState(is_screen_lock); setLockedState(is_screen_lock);
if (!screenlocked) { if (!screenlocked) {
hideFloatingWindow(); hideFloatingWindow();
} }
timelocked = false;
} }
// } else { // } else {
// if (!screenlocked) { // if (!screenlocked) {