refactor(core): 清理废弃基类/DTO/拦截器并优化 MMKV 与日志处理

This commit is contained in:
tongtong committed 2026-11-12 14:32:31 +08:00
1 parent d8742f18ff
commit 01dc9e2537
8 files changed
+9 -591

No files matched your search

@@ -1,57 +0,0 @@
package com.fuying.sn.core.base;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
/**
* DialogFragment 基类,提供与 {@link BaseFragment} 一致的懒加载入口。
*
* <p>Dialog 不在 ViewPager 中,可见性直接由自身生命周期决定,
* 因此不再实现已废弃的 {@code setUserVisibleHint()}。
*/
public abstract class BaseDialogFragment extends DialogFragment {
protected boolean isViewInitiated;
protected boolean isVisibleToUser;
protected boolean isDataInitiated;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
isViewInitiated = true;
prepareFetchData();
}
@Override
public void onResume() {
super.onResume();
isVisibleToUser = true;
prepareFetchData();
}
@Override
public void onPause() {
isVisibleToUser = false;
super.onPause();
}
public abstract void fetchData();
public boolean prepareFetchData() {
return prepareFetchData(false);
}
public boolean prepareFetchData(boolean forceUpdate) {
if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
fetchData();
//注释掉保证每次都更新数据
// isDataInitiated = true;
return true;
}
return false;
}
}
@@ -1,147 +0,0 @@
package com.fuying.sn.core.data.dto.app;
import android.graphics.drawable.Drawable;
import java.io.Serializable;
public class LocalAppInfo implements Serializable {
private static final long serialVersionUID = -189981552730429360L;
public static final int DOWNLOAD_STATUS_NORMAL = 0;
public static final int DOWNLOAD_STATUS_DOWNLOADING = 1;
public static final int DOWNLOAD_STATUS_PAUSE = 2;
private Drawable icon;
private String iconUrl = "";
private String appName;
private String packageName;
private String version;
private String latestVersion = "";
private int size;
private String latestSize;
private String downLoadUrl;
private int dowloadStatus = DOWNLOAD_STATUS_NORMAL;
private String tip;
private int id;
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}
public String getLatestSize() {
return latestSize;
}
public void setLatestSize(String latestSize) {
this.latestSize = latestSize;
}
public String getDownLoadUrl() {
return downLoadUrl;
}
public void setDownLoadUrl(String downLoadUrl) {
this.downLoadUrl = downLoadUrl;
}
public int getDowloadStatus() {
return dowloadStatus;
}
public void setDowloadStatus(int dowloadStatus) {
this.dowloadStatus = dowloadStatus;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
public boolean equals(Object obj) {
if (this == obj) //传入的对象就是它自己,如s.equals(s);肯定是相等的;
return true;
if (obj == null) //如果传入的对象是空,肯定不相等
return false;
if (getClass() != obj.getClass()) //如果不是同一个类型的,如Studnet类和Animal类,
//也不用比较了,肯定是不相等的
return false;
LocalAppInfo other = (LocalAppInfo) obj;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName)) //如果name属性相等,则相等
return false;
return true;
}
}
@@ -1,34 +0,0 @@
package com.fuying.sn.core.data.dto.statistics;
import java.io.Serializable;
public class AppUsed implements Serializable {
private static final long serialVersionUID = -317163343719361595L;
String packages;
long useTime;
String app_name;
public String getPackages() {
return packages;
}
public void setPackages(String packages) {
this.packages = packages;
}
public long getUseTime() {
return useTime;
}
public void setUseTime(long useTime) {
this.useTime = useTime;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
}
@@ -1,333 +0,0 @@
package com.fuying.sn.core.data.remote;
import android.util.Log;
import com.blankj.utilcode.util.EncryptUtils;
import com.fuying.sn.BuildConfig;
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;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* 重复请求拦截器。
*
* <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 {
private static final String TAG = "RepeatRequestInterceptor";
/**
* 等待进行中请求返回结果的最长时间,超时后本次请求自己访问服务器。
* 需要大于 OkHttpClient 的超时时间(当前为 5 秒)。
*/
private static final long WAIT_IN_FLIGHT_TIMEOUT_MS = 10_000L;
/**
* 请求完成后结果保留的时间。在该时间内收到相同请求,直接复用结果,不再访问服务器。
* 需要小于业务侧的刷新间隔(连接模式最小为 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
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
String bodyText = requestBodyToString(request.body());
String requestKey = buildRequestKey(request, bodyText);
clearExpiredRecords();
RepeatRecord record = acquireRecord(requestKey);
if (record == null) {
// 已有相同请求,但没有拿到可用结果(上一次失败、超时或结果过大),本次请求直接访问服务器
return chain.proceed(request);
}
if (!record.isOwner()) {
// 复用相同请求的结果:服务端只会收到一次请求
log("复用请求:", requestKey, request, bodyText);
return record.newResponse(request);
}
log("注册请求:", requestKey, request, bodyText);
try {
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
if (responseBody == null || responseBody.contentLength() > MAX_DEDUP_BODY_BYTES) {
// 无响应体或响应体过大:不消费 body,也不参与去重,直接透传
logResponse(request, null);
return response;
}
// 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 {
// 兜底:无论成功、失败还是异常,都结束记录,避免等待中的相同请求被一直阻塞
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<String, RepeatRecord> entry : recordMap.entrySet()) {
RepeatRecord record = entry.getValue();
if (record.isExpired(now)) {
recordMap.remove(entry.getKey(), record);
}
}
}
private static String buildRequestKey(Request request, String bodyText) {
return EncryptUtils.encryptMD5ToString(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) {
String body = bodyText;
if (bodyText.length() > MAX_LOG_BODY_LENGTH) {
body = "-too long";
}
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 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));
}
}
/**
* 一次请求的去重记录: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();
}
}
}
}
@@ -21,6 +21,8 @@ import java.util.HashSet;
*/
public class AppWhitelistUtils {
private static final MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
/**
* 更新应用白名单禁止升级
*
@@ -35,8 +37,7 @@ public class AppWhitelistUtils {
String upgrade_disallow = Settings.System.getString(context.getContentResolver(), CommonConfig.AOLE_ACTION_DISALLOW_UPGRADE);
//所有app
String only_jgy_shortcut_list = Settings.System.getString(context.getContentResolver(), CommonConfig.ONLY_SHORTCUT_LIST);
MMKV mmkv = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
String overall_app_list = mmkv.decodeString(CommonConfig.AOLE_ACTION_OVERALL_APP, "");
String overall_app_list = mMMKV.decodeString(CommonConfig.AOLE_ACTION_OVERALL_APP, "");
Log.e("writeDisableUpdateList", "aole_app_forbid: " + now);
HashSet<String> nowList = new HashSet<>();
HashSet<String> disallowList = new HashSet<>();
@@ -1,12 +0,0 @@
package com.fuying.sn.platform.control;
public enum ConnectMode {
DEFAULT,
ONE_MINUTE,
FIFTEEN_MINUTES,
HALF_HOUR,
ONE_HOUR,
SIX_HOUR,
HALF_DAY,
ONE_DAY,
}
@@ -19,7 +19,7 @@ public class ControlPanelManager {
private static ControlPanelManager sInstance;
private Context mContext;
private ContentResolver mResolver;
private MMKV mmkv;
private final MMKV mmkv = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
private UsbManager mUsbManager;
public static final String KEY_USB_STATUS = "KEY_USB_STATUS";
@@ -34,7 +34,6 @@ public class ControlPanelManager {
this.mContext = context;
this.mResolver = context.getContentResolver();
mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
mmkv = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
}
public static void init(Context context) {
@@ -9,11 +9,11 @@ import android.text.TextUtils;
import android.util.Log;
import com.fuying.sn.core.base.BaseService;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.remote.BackgroundRequests;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.remote.BackgroundRequests;
import com.fuying.sn.core.data.repository.DeviceRepository;
import java.io.BufferedReader;
import java.io.File;
@@ -194,6 +194,7 @@ public class LogcatService extends BaseService {
os = null;
} catch (IOException e) {
// 日志输出流关闭失败时,当前实现忽略该异常。
Log.e(TAG, "run: " + e.getMessage());
}
}
}