refactor(core): 统一应用管控评估逻辑并重构日志采集为会话模型

- TimeManager 提取 evaluateBlocking 统一运行时管控与桌面查询,避免两处判断不一致
- TimeManager 新增 inControlTime/getDisableContent 供外部桌面 AIDL 调用
- LogcatService 引入 LogSession 会话模型,每轮采集独立绑定配置与文件路径
- LogcatService 修复并发 START/STOP 时共享状态被覆盖导致的竞态问题
- RemoteService 调用来源从 RunningAppManager 迁移至 TimeManager
- MainService NTP 校时增加 null/负值校验,防止将系统时间写入 1969 年
- TimeManager Toast 相关字段添加 volatile 修饰保证多线程可见性
This commit is contained in:
tongtong committed 2026-11-21 15:42:07 +08:00
1 parent 6712fbdb75
commit 2bfcb80dc5
4 files changed
+217 -108

No files matched your search

@@ -25,6 +25,7 @@ import com.fuying.sn.core.common.sync.DeviceSyncGateway;
import com.fuying.sn.core.common.sync.DeviceSyncGateways;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.core.data.dto.device.SnInfo;
import com.fuying.sn.core.data.dto.statistics.RemainTime;
import com.fuying.sn.core.data.dto.time.AppTimeControlInfo;
import com.fuying.sn.core.data.dto.time.PartTime;
import com.fuying.sn.core.data.dto.time.SnTimeControlInfo;
@@ -122,8 +123,8 @@ public class TimeManager {
*/
private long mLastRemainingDbWrite = 0;
private static final long REMAINING_WRITE_INTERVAL = 5000; // 节流间隔 5 秒
private String mLastToastMessage;
private long mLastToastTime = 0;
private volatile String mLastToastMessage;
private volatile long mLastToastTime = 0;
private static final long TOAST_INTERVAL = 5000; // 同一拦截提示 5 秒内只弹一次
/**
@@ -434,72 +435,139 @@ public class TimeManager {
* @return true 允许运行,false 触发拦截
*/
public boolean appCanRun(String pkg) {
if (ApkUtils.isSystemApp(mContext, pkg)) return true;
if (isPackageExempted(pkg)) return true;
if (mSnTimeControlInfo == null) return false;
return evaluateBlocking(pkg, true, true) == null;
}
/**
* 供外部桌面查询应用是否被管控。
*
* <p>与 {@link #appCanRun(String)} 共用同一套运行时配置,返回 true 表示当前不允许启动,
* 保持旧 AIDL 接口的语义不变。
*
* @param pkg 应用包名
* @return true 被管控(不允许启动),false 允许启动
*/
public boolean inControlTime(String pkg) {
// 配置未就绪时不做拦截,与旧实现及每秒循环的守卫保持一致
return evaluateBlocking(pkg, true, false) != null;
}
/**
* 供外部桌面获取拦截原因。
*
* <p>允许运行时返回空串,保持旧接口约定;拦截时返回 RemainTime 的 JSON,
* disableType 含义与历史版本一致:1 应用被禁用、2 应用时长用完、
* 3 不在可用时间段、4 整机时长用完。
*
* @param pkg 应用包名
* @return 拦截信息 JSON,允许运行时为空串
*/
public String getDisableContent(String pkg) {
BlockReason reason = evaluateBlocking(pkg, false, false);
if (reason == null) {
return "";
}
RemainTime remainTime = new RemainTime();
remainTime.setPkg(pkg);
remainTime.setDisableType(reason.disableType);
remainTime.setContent(reason.content);
remainTime.setTotalTime(reason.totalTime);
remainTime.setAvailableTime(reason.availableTime);
return remainTime.toString();
}
/**
* 统一评估应用是否被拦截,供运行时管控与外部桌面查询复用,避免两处判断结果不一致。
*
* @param pkg 应用包名
* @param showToast 是否弹出拦截提示
* @param blockWhenConfigMissing 配置未就绪时是否按拦截处理(运行时管控为 true,外部查询为 false)
* @return 拦截原因;允许运行时返回 null
*/
private BlockReason evaluateBlocking(String pkg, boolean showToast, boolean blockWhenConfigMissing) {
if (TextUtils.isEmpty(pkg)) {
return null;
}
if (ApkUtils.isSystemApp(mContext, pkg)) {
return null;
}
if (isPackageExempted(pkg)) {
return null;
}
if (mSnTimeControlInfo == null) {
if (blockWhenConfigMissing) {
return new BlockReason(0, "", 0, 0);
}
return null;
}
AppTimeControlInfo appInfo = mAppTimeControlMap.get(pkg);
if (appInfo == null) {
// 未下发独立配置的应用不拦截,同时触发安装清单补偿上报
syncInstalledAppsOnCacheMiss();
return true;
return null;
}
// 应用是否被手动禁用 (is_control == 0)
if (appInfo.getIs_control() == 0) {
showControlToast("应用已被禁用");
return false;
return blocked(1, "应用已被禁用", appInfo.getToday_time(), 0, showToast);
}
// A. 校验整机(SN)层级的限制
if (!checkSnLevelControl()) return false;
// A. 整机(SN)层级:时长模式
if (mSnTimeControlInfo.getControl_type() == 1 && mGlobalRemainingTime <= 0) {
return blocked(4, "今日整机使用时长已超限",
mSnTimeControlInfo.getToday_time(), mGlobalRemainingTime, showToast);
}
// B. 整机(SN)层级:时间段模式
if (mSnTimeControlInfo.getControl_type() == 2) {
List<PartTime> snParts = mSnTimeControlInfo.getTime_part();
if (!isDefaultTimePeriod(snParts) && !inOpenTimePeriod(snParts)) {
return blocked(3, "当前时间不在设备的可使用时间段内", 0, 0, showToast);
}
}
// B. 校验应用(App)自身的独立限制
return checkAppLevelControl(pkg, appInfo);
// C. 应用(App)级别:时长模式
if (appInfo.getControl_type() == 1) {
Long remain = mRemainingTimeMap.get(pkg);
long available = 0;
if (remain != null) {
available = remain;
}
if (available <= 0) {
return blocked(2, "今日该应用使用时长已超限", appInfo.getToday_time(), available, showToast);
}
}
// D. 应用(App)级别:时间段模式
if (appInfo.getControl_type() == 2) {
if (!inOpenTimePeriod(appInfo.getTime_part())) {
return blocked(3, "当前时间不在应用的可使用时间段内", 0, 0, showToast);
}
}
return null;
}
private BlockReason blocked(int disableType, String content, long totalTime, long availableTime, boolean showToast) {
if (showToast) {
showControlToast(content);
}
return new BlockReason(disableType, content, totalTime, availableTime);
}
/**
* 整机(SN)级别管控逻辑:时长模式或时间段模式
* 拦截原因,用于统一运行时管控与外部桌面查询的结果。
*/
private boolean checkSnLevelControl() {
int snType = mSnTimeControlInfo.getControl_type();
switch (snType) {
case 1: // 整机限时:如果整机时间耗尽,则拦截(无论应用是否开启独立时长)
if (mGlobalRemainingTime <= 0) {
showControlToast("今日整机使用时长已超限");
return false;
}
break;
case 2: // 整机限时间段:当前时间需在整机允许的时间段内
List<PartTime> snParts = mSnTimeControlInfo.getTime_part();
if (!isDefaultTimePeriod(snParts) && !inOpenTimePeriod(snParts)) {
showControlToast("当前时间不在设备的可使用时间段内");
return false;
}
break;
}
return true;
}
private static final class BlockReason {
final int disableType;
final String content;
final long totalTime;
final long availableTime;
/**
* 应用(App)级别管控逻辑:独立时长或独立时间段
*/
private boolean checkAppLevelControl(String pkg, AppTimeControlInfo appInfo) {
switch (appInfo.getControl_type()) {
case 1: // 应用时长限制:检查该应用剩余时长
Long remain = mRemainingTimeMap.get(pkg);
if (remain == null || remain <= 0) {
showControlToast("今日该应用使用时长已超限");
return false;
}
break;
case 2: // 应用时间段限制:检查当前是否在应用允许的时间段
if (!inOpenTimePeriod(appInfo.getTime_part())) {
showControlToast("当前时间不在应用的可使用时间段内");
return false;
}
break;
BlockReason(int disableType, String content, long totalTime, long availableTime) {
this.disableType = disableType;
this.content = content;
this.totalTime = totalTime;
this.availableTime = availableTime;
}
return true;
}
/**
@@ -112,34 +112,66 @@ public class LogcatService extends BaseService {
ReceiverCompat.registerReceiver(this, receiver, filter, ReceiverCompat.RECEIVER_EXPORTED);
}
private volatile Thread thread = null;
// 当前采集进程,STOP 时销毁它,打断阻塞中的 readLine
private volatile Process mLogProcess = null;
/**
* 一轮日志采集的独立上下文:配置、输出文件与进程都跟本轮绑定,
* 上一轮收尾不会再被下一轮的 START 覆盖或阻塞。
*/
private static class LogSession {
final String filePath;
final long startTime;
final long duration;
final long maxFileSize;
final boolean clearFile;
volatile boolean running = true;
volatile Process process;
private synchronized void startLogThread() {
if (thread != null) {
Log.e(TAG, "startLogThread: already running");
return;
LogSession(String filePath, long startTime, long duration, long maxFileSize, boolean clearFile) {
this.filePath = filePath;
this.startTime = startTime;
this.duration = duration;
this.maxFileSize = maxFileSize;
this.clearFile = clearFile;
}
shouldGetLog = true;
// 常驻采集线程:命名便于排查,设为守护线程避免进程退出时被它拖住
thread = new Thread(LogcatRunnale, "Logcat-Collector");
thread.setDaemon(true);
thread.start();
}
private final Object mSessionLock = new Object();
// 当前正在进行的采集轮次;STOP 后立即摘除,使紧接着的 START 能正常开始
private LogSession mActiveSession;
private void startLogThread() {
LogSession session;
synchronized (mSessionLock) {
if (mActiveSession != null) {
Log.e(TAG, "startLogThread: already running");
return;
}
session = new LogSession(logFilePath, start_Time, condition_duration,
condition_file_max_size, clear_file);
mActiveSession = session;
}
// 每轮独立线程,上一轮尚未走完 finally 时也不会挡住新的 START
Thread worker = new Thread(() -> getLog(session), "Logcat-Collector");
worker.setDaemon(true);
worker.start();
}
private void stopLogThread() {
Process process;
synchronized (this) {
shouldGetLog = false;
process = mLogProcess;
LogSession session;
synchronized (mSessionLock) {
session = mActiveSession;
if (session == null) {
// 本轮已结束并在 finally 中完成上传,避免重复上传
return;
}
// 先摘除当前轮次,后续 START 可以立即开始新的一轮
mActiveSession = null;
session.running = false;
}
if (process == null) {
// 采集线程已结束并在 finally 中完成上传,避免重复上传
return;
Process process = session.process;
if (process != null) {
// 销毁进程打断 readLine,收尾与上传由该轮采集线程的 finally 处理
process.destroy();
}
// 销毁进程打断 readLine,收尾与上传由采集线程的 finally 统一处理
process.destroy();
}
private void clearLogcatBuffer() {
@@ -174,7 +206,6 @@ public class LogcatService extends BaseService {
String logFilePath;
//= getExternalCacheDir() + File.separator + "LOG" + File.separator;
String logFileName;
String tempFilePath;
class LogThread extends Thread {
InputStream is;
@@ -219,36 +250,37 @@ public class LogcatService extends BaseService {
}
}
private Runnable LogcatRunnale = this::getLog;
public static volatile boolean shouldGetLog = true;
private void getLog() {
private void getLog(LogSession session) {
Process process = null;
BufferedReader bufferedReader = null;
FileOutputStream fileOutputStream = null;
tempFilePath = null;
String tempFilePath = null;
try {
process = Runtime.getRuntime().exec(running);
mLogProcess = process;
File file = new File(logFilePath);
Log.e(TAG, "getLog: " + logFilePath);
if (!file.exists()) {
file.mkdirs();
session.process = process;
if (!session.running) {
// STOP 在进程启动前已到达,直接进入收尾
return;
}
File dir = new File(session.filePath);
Log.e(TAG, "getLog: " + session.filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (clear_file) {
String logFileName;
if (session.clearFile) {
logFileName = DeviceIdUtils.getSerial() + ".log";
} else {
logFileName = DeviceIdUtils.getSerial() + "-" + getTime() + ".log";
}
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
tempFilePath = logFilePath + logFileName;
tempFilePath = session.filePath + logFileName;
fileOutputStream = new FileOutputStream(tempFilePath);
Log.e(TAG, "getLog: " + tempFilePath);
long fileSize = new File(tempFilePath).length();
while (shouldGetLog) {
while (session.running) {
String line = bufferedReader.readLine();
if (line == null) {
// logcat 进程被销毁或异常退出,结束本轮采集
@@ -258,9 +290,9 @@ public class LogcatService extends BaseService {
fileOutputStream.write(logEntry.getBytes());
fileOutputStream.flush();
fileSize += logEntry.length();
if (fileSize >= condition_file_max_size ||
(start_Time + condition_duration) * 1000 < System.currentTimeMillis()) {
shouldGetLog = false;
if (fileSize >= session.maxFileSize ||
(session.startTime + session.duration) * 1000 < System.currentTimeMillis()) {
session.running = false;
}
}
Log.e(TAG, "getLog: closed");
@@ -271,28 +303,32 @@ public class LogcatService extends BaseService {
} finally {
closeQuietly(bufferedReader);
closeQuietly(fileOutputStream);
session.process = null;
if (process != null) {
process.destroy();
}
synchronized (this) {
if (thread == Thread.currentThread()) {
thread = null;
shouldGetLog = false;
boolean clearBuffer;
synchronized (mSessionLock) {
if (mActiveSession == session) {
mActiveSession = null;
}
mLogProcess = null;
// 已有新一轮采集时不清 adb 缓冲,避免影响新采集
clearBuffer = mActiveSession == null;
}
// 文件流关闭后再统一清 adb 缓存并上传,避免上传到不完整文件
clearLogcatBuffer();
uploadFile();
if (clearBuffer) {
clearLogcatBuffer();
}
// 使用本轮自己的文件路径上传,避免被下一轮覆盖
uploadFile(tempFilePath, session.clearFile);
}
}
private void uploadFile() {
if (TextUtils.isEmpty(tempFilePath)) {
Log.e(TAG, "uploadFile: tempFilePath is empty");
private void uploadFile(String uploadFilePath, final boolean clearAfterUpload) {
if (TextUtils.isEmpty(uploadFilePath)) {
Log.e(TAG, "uploadFile: uploadFilePath is empty");
return;
}
File file = new File(tempFilePath);
File file = new File(uploadFilePath);
if (!file.exists() || file.isDirectory()) {
Log.e(TAG, "uploadFile: File does not exists");
return;
@@ -319,7 +355,7 @@ public class LogcatService extends BaseService {
@Override
public void onComplete() {
Log.e(TAG, "uploadFile: onComplete: ");
if (clear_file) {
if (clearAfterUpload) {
file.delete();
}
}
@@ -10,7 +10,7 @@ import android.util.Log;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.IGetInfoInterface;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.platform.app.RunningAppManager;
import com.fuying.sn.platform.time.TimeManager;
public class RemoteService extends Service {
private static final String TAG = "RemoteService";
@@ -51,14 +51,14 @@ public class RemoteService extends Service {
@Override
public boolean inControl(String pkg) throws RemoteException {
boolean control = RunningAppManager.getInstance().inControlTime(pkg);
boolean control = TimeManager.getInstance().inControlTime(pkg);
Log.e(TAG, "inControl: " + control);
return control;
}
@Override
public String getDisableContent(String pkg) throws RemoteException {
String content = RunningAppManager.getInstance().getDisableContent(pkg);
String content = TimeManager.getInstance().getDisableContent(pkg);
if (BuildConfig.DEBUG) {
Log.e(TAG, "getDisableContent: " + content);
}
@@ -345,8 +345,13 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
super.onPostExecute(aLong);
// AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// am.setTime(aLong);
SystemClock.setCurrentTimeMillis(aLong);
Log.e(TAG, "getTimeFromNtpServer: " + aLong);
// 校准失败时 TimeUtils 返回 -1,必须拦下,否则会把整机时间写到 1969 年
if (aLong == null || aLong <= 0) {
Log.e(TAG, "NTPTimeTask: 校时失败,保持系统时间不变");
return;
}
boolean success = SystemClock.setCurrentTimeMillis(aLong);
Log.e(TAG, "getTimeFromNtpServer: " + aLong + ", set success = " + success);
}
}