From 1a2525176a489d6143432e80c2429d1838c7cfb3 Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Sat, 21 Nov 2026 16:32:45 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E8=90=BD=E7=9B=98=E3=80=81=E7=BA=BF=E7=A8=8B=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=8F=B0=E6=9C=8D=E5=8A=A1=E5=81=A5=E5=A3=AE?= =?UTF-8?q?=E6=80=A7=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CacheHelper: put 先 flush/close 再 commit,关闭 reader,缓存实例为空时安全降级,日志不再打印完整内容 - TimeManager: 配置回调切回主线程,系统应用改内存表判断,缺清单上报切 IO - LogcatService/RemoteDiagnostics: START 兜底时长、按字节统计大小、私有 action + setPackage、STOP 按当前时间起算 - CmdUtil: 并发读取 stdout/stderr 避免死锁,增加执行超时 - PushManager/DeviceRepository/AppInventorySync/AppUsageReporter: 磁盘与 PackageManager 操作移出回调线程和缓存锁 - ManagerService: 订阅纳入 CompositeDisposable,去掉 TIME_TICK 重复的权限检查与无效 View 创建 - AndroidManifest/BootReceiver: 移除无法静态接收的 BATTERY_LEVEL_CHANGED --- app/src/main/AndroidManifest.xml | 1 - .../sn/core/data/local/cache/CacheHelper.java | 84 +++++++++++++++-- .../data/repository/DeviceRepository.java | 77 ++++++++------- .../com/fuying/sn/platform/app/ApkUtils.java | 4 + .../fuying/sn/platform/system/CmdUtil.java | 79 +++++++++++++--- .../time/FuyingActivityController.java | 11 ++- .../fuying/sn/platform/time/TimeManager.java | 94 ++++++++++++++++--- .../fuying/sn/runtime/push/PushManager.java | 18 ++-- .../sn/runtime/receiver/BootReceiver.java | 1 - .../sn/runtime/service/LogcatService.java | 38 ++++++-- .../sn/runtime/service/ManagerService.java | 30 ++---- .../sn/runtime/sync/AppInventorySync.java | 10 +- .../sn/runtime/sync/AppUsageReporter.java | 15 ++- .../sn/runtime/sync/RemoteDiagnostics.java | 17 +++- 14 files changed, 359 insertions(+), 120 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 947be01..7d11249 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -154,7 +154,6 @@ - request = networkObservable .subscribeOn(Schedulers.io()) .doOnNext(value -> { + // 只在锁内确认请求仍是当前有效请求,缓存写入(含磁盘)放到锁外执行, + // 避免磁盘 IO 期间一直占着 CACHE_LOCK。 + boolean isCurrent; synchronized (CACHE_LOCK) { // 已作废的请求仍可能返回,但不能把旧结果重新写入缓存。 - if (IN_FLIGHT_REQUESTS.get(cacheKey) == self.get()) { - cacheResult.accept(value); - } + isCurrent = IN_FLIGHT_REQUESTS.get(cacheKey) == self.get(); + } + if (isCurrent) { + cacheResult.accept(value); } }) .doOnError(error -> { + boolean isCurrent; synchronized (CACHE_LOCK) { - if (IN_FLIGHT_REQUESTS.get(cacheKey) == self.get()) { - cacheError.accept(error); - } + isCurrent = IN_FLIGHT_REQUESTS.get(cacheKey) == self.get(); + } + if (isCurrent) { + cacheError.accept(error); } }) .doFinally(() -> { @@ -205,37 +211,36 @@ public final class DeviceRepository { Observable> withMultiLevelCache( Observable> network, String key, Type type, long ttlMillis) { return scheduleForCache(key, Observable.defer(() -> { - synchronized (CACHE_LOCK) { - BaseResponse fresh = CACHE_MANAGER.getCache(key); - if (fresh != null) { - return Observable.just(fresh); - } - BaseResponse stale = readDisk(key, type); - Observable> refresh = Observable.defer(() -> { - synchronized (CACHE_LOCK) { - // 发出磁盘数据后再次检查内存,复用其他订阅刚刷新的结果。 - BaseResponse cached = CACHE_MANAGER.getCache(key); - if (cached != null) { - return Observable.just(cached); - } - return joinInFlight(key, network, value -> { - if (value.code == 200 && value.data != null) { - CACHE_MANAGER.saveCache(key, value, ttlMillis); - diskCache.put(key, GsonUtils.toJSONString(value)); - } else { - clearCachedValues(key); - } - }, error -> { - Log.e(TAG, "withMultiLevelCache: refresh failed for " + key, error); - clearCachedValues(key); - }); - } - }); - if (stale == null) { - return refresh; - } - return Observable.just(stale).concatWith(refresh); + BaseResponse fresh = CACHE_MANAGER.getCache(key); + if (fresh != null) { + return Observable.just(fresh); } + // 磁盘读取是真正的 IO,不能放在 CACHE_LOCK 内阻塞其他缓存的读写 + BaseResponse stale = readDisk(key, type); + Observable> refresh = Observable.defer(() -> { + synchronized (CACHE_LOCK) { + // 发出磁盘数据后再次检查内存,复用其他订阅刚刷新的结果。 + BaseResponse cached = CACHE_MANAGER.getCache(key); + if (cached != null) { + return Observable.just(cached); + } + return joinInFlight(key, network, value -> { + if (value.code == 200 && value.data != null) { + CACHE_MANAGER.saveCache(key, value, ttlMillis); + diskCache.put(key, GsonUtils.toJSONString(value)); + } else { + clearCachedValues(key); + } + }, error -> { + Log.e(TAG, "withMultiLevelCache: refresh failed for " + key, error); + clearCachedValues(key); + }); + } + }); + if (stale == null) { + return refresh; + } + return Observable.just(stale).concatWith(refresh); })); } diff --git a/app/src/main/java/com/fuying/sn/platform/app/ApkUtils.java b/app/src/main/java/com/fuying/sn/platform/app/ApkUtils.java index 466679b..aa430ae 100644 --- a/app/src/main/java/com/fuying/sn/platform/app/ApkUtils.java +++ b/app/src/main/java/com/fuying/sn/platform/app/ApkUtils.java @@ -533,6 +533,10 @@ public class ApkUtils { */ public static boolean isSystemApp(Context context, String pkgName) { boolean isSystemApp = false; + if (context == null || TextUtils.isEmpty(pkgName)) { + Log.e(TAG, "isSystemApp: invalid param, pkgName = " + pkgName); + return false; + } PackageInfo pi = null; try { PackageManager pm = context.getPackageManager(); diff --git a/app/src/main/java/com/fuying/sn/platform/system/CmdUtil.java b/app/src/main/java/com/fuying/sn/platform/system/CmdUtil.java index 96109ff..5cf0a6b 100644 --- a/app/src/main/java/com/fuying/sn/platform/system/CmdUtil.java +++ b/app/src/main/java/com/fuying/sn/platform/system/CmdUtil.java @@ -6,7 +6,9 @@ import android.util.Log; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; +import java.util.concurrent.TimeUnit; public class CmdUtil { private static final String TAG = "CmdUtil"; @@ -14,6 +16,9 @@ public class CmdUtil { private static final String COMMAND_SH = "sh"; private static final String COMMAND_EXIT = "exit\n"; private static final String COMMAND_LINE_END = "\n"; + // 命令执行超时时间,避免异常命令把调用线程一直挂住 + private static final long EXEC_TIMEOUT_MS = 15000L; + private static final long READ_TIMEOUT_MS = 2000L; /** @@ -33,6 +38,8 @@ public class CmdUtil { Process process = null; DataOutputStream dos = null; + StreamCollector outCollector = null; + StreamCollector errCollector = null; try { process = Runtime.getRuntime().exec(COMMAND_SH); @@ -42,16 +49,31 @@ public class CmdUtil { dos.flush(); dos.writeBytes(COMMAND_EXIT); dos.flush(); - result.code = process.waitFor(); - result.success = readBuffer(new BufferedReader(new InputStreamReader(process.getInputStream()))); - result.error = readBuffer(new BufferedReader(new InputStreamReader(process.getErrorStream()))); + dos.close(); + dos = null; + // 必须先并发读走 stdout/stderr,再 waitFor;否则输出量大时管道写满会死锁 + outCollector = new StreamCollector(process.getInputStream(), "CmdUtil-out"); + errCollector = new StreamCollector(process.getErrorStream(), "CmdUtil-err"); + outCollector.start(); + errCollector.start(); + + if (process.waitFor(EXEC_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + result.code = process.exitValue(); + } else { + Log.e(TAG, "execute: timeout after " + EXEC_TIMEOUT_MS + "ms, destroy process"); + result.code = Result.ERROR; + } + + outCollector.join(READ_TIMEOUT_MS); + errCollector.join(READ_TIMEOUT_MS); + result.success = outCollector.getContent(); + result.error = errCollector.getContent(); Log.e(TAG, "result = " + result); } catch (IOException ioe) { Log.e(TAG, "execute: " + ioe.getMessage(), ioe); - Log.e(TAG, ioe.getMessage()); } catch (InterruptedException ie) { Log.e(TAG, "execute: " + ie.getMessage(), ie); - Log.e(TAG, ie.getMessage()); + Thread.currentThread().interrupt(); } finally { try { if (null != dos) { @@ -59,7 +81,6 @@ public class CmdUtil { } } catch (IOException ioe) { Log.e(TAG, "execute: " + ioe.getMessage(), ioe); - Log.e(TAG, ioe.getMessage()); } if (null != process) { process.destroy(); @@ -68,13 +89,46 @@ public class CmdUtil { return result; } - private static String readBuffer(BufferedReader bufferedReader) throws IOException { - StringBuilder sb = new StringBuilder(); - String s; - while ((s = bufferedReader.readLine()) != null) { - sb.append(s); + /** + * 独立线程读取进程的一个输出流,避免主流程等待时管道缓冲区被写满。 + */ + private static final class StreamCollector extends Thread { + private final InputStream inputStream; + private final StringBuilder content = new StringBuilder(); + + StreamCollector(InputStream inputStream, String name) { + super(name); + this.inputStream = inputStream; + setDaemon(true); + } + + @Override + public void run() { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(inputStream)); + String line; + while ((line = reader.readLine()) != null) { + content.append(line); + } + } catch (IOException e) { + Log.e(TAG, "StreamCollector.run: " + e.getMessage(), e); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + Log.e(TAG, "StreamCollector.run: " + e.getMessage(), e); + } + } + } + } + + String getContent() { + synchronized (content) { + return content.toString(); + } } - return sb.toString(); } @@ -100,4 +154,3 @@ public class CmdUtil { } } } - diff --git a/app/src/main/java/com/fuying/sn/platform/time/FuyingActivityController.java b/app/src/main/java/com/fuying/sn/platform/time/FuyingActivityController.java index 235898e..e365ad8 100644 --- a/app/src/main/java/com/fuying/sn/platform/time/FuyingActivityController.java +++ b/app/src/main/java/com/fuying/sn/platform/time/FuyingActivityController.java @@ -13,12 +13,13 @@ public class FuyingActivityController extends IActivityController.Stub { @Override public boolean activityStarting(Intent intent, String pkg) { - Log.e(TAG, "activityStarting: " + pkg + ", intent= " + intent); - boolean allowStart = TimeManager.getInstance().appCanRun(pkg); - if (!allowStart) { -// Toaster.show(pkg + ""); + // 包名为空时无法判断,直接放行,避免误拦截系统启动流程 + if (pkg == null || pkg.isEmpty()) { + Log.e(TAG, "activityStarting: pkg is empty, allow"); + return true; } - return allowStart; + Log.e(TAG, "activityStarting: " + pkg); + return TimeManager.getInstance().appCanRun(pkg); } @Override diff --git a/app/src/main/java/com/fuying/sn/platform/time/TimeManager.java b/app/src/main/java/com/fuying/sn/platform/time/TimeManager.java index 185ee02..aae644f 100644 --- a/app/src/main/java/com/fuying/sn/platform/time/TimeManager.java +++ b/app/src/main/java/com/fuying/sn/platform/time/TimeManager.java @@ -10,6 +10,7 @@ import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; @@ -46,10 +47,12 @@ import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; @@ -80,6 +83,12 @@ public class TimeManager { */ private final TimeConfigRepository mConfigRepository = TimeConfigRepository.getInstance(); + /** + * 配置仓库回调线程不确定,统一切回主线程再改运行时状态, + * 避免与每秒检测循环并发读写同一个 Map。 + */ + private final Handler mMainHandler = new Handler(Looper.getMainLooper()); + private SnTimeControlInfo mSnTimeControlInfo; @@ -91,7 +100,7 @@ public class TimeManager { /** * 记录整机(SN)当前剩余可用时长(秒) */ - private long mGlobalRemainingTime; + private volatile long mGlobalRemainingTime; /** * 记录每个受限应用的当前剩余可用时长(秒) @@ -152,6 +161,13 @@ public class TimeManager { } }; + /** + * 系统应用包名缓存。 + * ActivityController 的 activityStarting 运行在 system_server 回调中, + * 不能每次都走 PackageManager 查询,这里启动后在 IO 线程扫描一次供运行时快速判断。 + */ + private volatile Set mSystemPackages = Collections.emptySet(); + private TimeManager(Context context) { if (context == null) { throw new RuntimeException("Context is NULL"); @@ -166,6 +182,7 @@ public class TimeManager { initActivityController(); initUidImportanceListener(); loadLocalConfig(); + loadSystemPackagesAsync(); mLastProcessedDate = LocalDate.now(); getTimeControl(); // 异步同步服务端配置 @@ -230,7 +247,8 @@ public class TimeManager { // 先抢占窗口再提交网络任务,避免并发的名单检查同时发起上报。 if (now >= nextFallbackAt && mNextAppListFallbackAt.compareAndSet(nextFallbackAt, now + APP_LIST_FALLBACK_INTERVAL_MS)) { - uploadInstalledApps(); + // 上报需要扫描安装列表并走网络,不能在 ActivityController 的调用线程同步执行 + Schedulers.io().scheduleDirect(this::uploadInstalledApps); } } @@ -419,6 +437,40 @@ public class TimeManager { decrementUsageTime(pkg); } + /** + * 后台扫描一次系统应用包名,供 {@link #isSystemPackage(String)} 纯内存判断。 + */ + private void loadSystemPackagesAsync() { + Schedulers.io().scheduleDirect(() -> { + try { + List apps = mPackageManager.getInstalledApplications(0); + Set result = new HashSet<>(); + if (apps != null) { + for (ApplicationInfo info : apps) { + if (info == null || TextUtils.isEmpty(info.packageName)) { + continue; + } + int flags = info.flags; + if ((flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) { + result.add(info.packageName); + } + } + } + mSystemPackages = result; + Log.e(TAG, "loadSystemPackagesAsync: size = " + result.size()); + } catch (Exception e) { + Log.e(TAG, "loadSystemPackagesAsync: " + e.getMessage(), e); + } + }); + } + + /** + * 纯内存判断是否系统应用,避免在 system_server 回调里同步查询 PackageManager。 + */ + private boolean isSystemPackage(String pkg) { + return mSystemPackages.contains(pkg); + } + /** * 判断包名是否在豁免管控名单中或管控功能已关闭 */ @@ -488,7 +540,7 @@ public class TimeManager { if (TextUtils.isEmpty(pkg)) { return null; } - if (ApkUtils.isSystemApp(mContext, pkg)) { + if (isSystemPackage(pkg)) { return null; } if (isPackageExempted(pkg)) { @@ -747,26 +799,20 @@ public class TimeManager { /** * 配置仓库监听:配置拉取成功后同步刷新 TimeManager 的运行时状态。 + * 回调可能发生在 IO 线程,统一 post 到主线程后再修改运行时状态。 */ private final TimeConfigRepository.OnConfigChangedListener mConfigListener = new TimeConfigRepository.OnConfigChangedListener() { @Override public void onSnConfigUpdated(SnTimeControlInfo info) { Log.e(TAG, "onSnConfigUpdated: " ); - mSnTimeControlInfo = info; - // 用服务端当日配额重置整机剩余时长 - mGlobalRemainingTime = info.getToday_time(); - mConfigRepository.saveGlobalRemainingTime(mGlobalRemainingTime); + mMainHandler.post(() -> applySnConfigUpdated(info)); } @Override public void onAppConfigUpdated(List list) { Log.e(TAG, "onAppConfigUpdated: " ); - // 配置已更新,启动时的 Room 恢复结果即使稍后返回也应丢弃 - mConfigVersion++; - rebuildAppMaps(list); - // 新配置下发后,用当日配额刷新 Room 剩余时长表 - saveAllRemainingToDb(); + mMainHandler.post(() -> applyAppConfigUpdated(list)); } @Override @@ -782,6 +828,30 @@ public class TimeManager { } }; + /** + * 应用整机配置(主线程执行)。 + */ + private void applySnConfigUpdated(SnTimeControlInfo info) { + if (info == null) { + return; + } + mSnTimeControlInfo = info; + // 用服务端当日配额重置整机剩余时长 + mGlobalRemainingTime = info.getToday_time(); + mConfigRepository.saveGlobalRemainingTime(mGlobalRemainingTime); + } + + /** + * 应用应用级配置(主线程执行)。 + */ + private void applyAppConfigUpdated(List list) { + // 配置已更新,启动时的 Room 恢复结果即使稍后返回也应丢弃 + mConfigVersion++; + rebuildAppMaps(list); + // 新配置下发后,用当日配额刷新 Room 剩余时长表 + saveAllRemainingToDb(); + } + // --- 广播监听 --- // 跟随 Application 常驻,进程退出由系统回收;显式销毁时使用同一实例注销。 diff --git a/app/src/main/java/com/fuying/sn/runtime/push/PushManager.java b/app/src/main/java/com/fuying/sn/runtime/push/PushManager.java index 8fb6544..c49eae2 100644 --- a/app/src/main/java/com/fuying/sn/runtime/push/PushManager.java +++ b/app/src/main/java/com/fuying/sn/runtime/push/PushManager.java @@ -777,8 +777,11 @@ public class PushManager { ToastUtil.debugShow("forceKillApp 缺少 app_package"); return; } - JgyUtils.getInstance().killPackage(packages); - JgyUtils.getInstance().gotoLauncher(); + // killPackage 内部通过 shell 同步等待命令结束,不能阻塞推送回调线程 + Schedulers.io().scheduleDirect(() -> { + JgyUtils.getInstance().killPackage(packages); + JgyUtils.getInstance().gotoLauncher(); + }); Log.e(TAG, "forceKillApp: " + extras); } @@ -1139,9 +1142,12 @@ public class PushManager { */ private void updateUserSettings(boolean invalidateSnInfo) { Log.e(TAG, "updateUserSettings: "); - DeviceRepository.removeCache(UrlAddress.GET_SETTINGS); - DeviceRepository.removeCache(UrlAddress.SN_TIME_CONTROL); - DeviceRepository.removeCache(UrlAddress.APP_TIME_CONTROL); + // removeCache 会删磁盘文件,推送回调线程不能同步执行,切到 IO 线程 + Schedulers.io().scheduleDirect(() -> { + DeviceRepository.removeCache(UrlAddress.GET_SETTINGS); + DeviceRepository.removeCache(UrlAddress.SN_TIME_CONTROL); + DeviceRepository.removeCache(UrlAddress.APP_TIME_CONTROL); + }); // 标记只在主线程读写,避免 SDK 回调线程与主线程并发修改 mMainHandler.post(() -> enqueueUserSettingsRefresh(invalidateSnInfo)); } @@ -1159,7 +1165,7 @@ public class PushManager { // 否则一次推送仍会跑两轮完整同步。 if (mPendingInvalidateSnInfo) { mPendingInvalidateSnInfo = false; - DeviceRepository.removeCache(UrlAddress.SN_INFO); + Schedulers.io().scheduleDirect(() -> DeviceRepository.removeCache(UrlAddress.SN_INFO)); } Log.e(TAG, "enqueueUserSettingsRefresh: 距上次刷新不足防抖窗口,合并本次请求"); return; diff --git a/app/src/main/java/com/fuying/sn/runtime/receiver/BootReceiver.java b/app/src/main/java/com/fuying/sn/runtime/receiver/BootReceiver.java index f43b323..ca22478 100644 --- a/app/src/main/java/com/fuying/sn/runtime/receiver/BootReceiver.java +++ b/app/src/main/java/com/fuying/sn/runtime/receiver/BootReceiver.java @@ -26,7 +26,6 @@ BootReceiver extends BroadcastReceiver { case Intent.ACTION_BOOT_COMPLETED: KVStore.encode(CommonConfig.DEVICES_REBOOT, true); case BOOT_COMPLETED: - case "android.intent.action.BATTERY_LEVEL_CHANGED": context.startService(new Intent(context, MainService.class)); context.startService(new Intent(context, SocketService.class)); context.startService(new Intent(context, DownloadService.class)); diff --git a/app/src/main/java/com/fuying/sn/runtime/service/LogcatService.java b/app/src/main/java/com/fuying/sn/runtime/service/LogcatService.java index 04c2ae3..6b5c4f2 100644 --- a/app/src/main/java/com/fuying/sn/runtime/service/LogcatService.java +++ b/app/src/main/java/com/fuying/sn/runtime/service/LogcatService.java @@ -22,6 +22,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; @@ -34,9 +35,13 @@ import okhttp3.RequestBody; public class LogcatService extends BaseService { private final DeviceRepository mRepository = DeviceRepository.getInstance(); - public final static String LOGCAT_START_ACTION = "START"; - public final static String LOGCAT_STOP_ACTION = "STOP"; + // 改成本应用私有 action,避免任意应用发送同名广播启停采集 + public final static String LOGCAT_START_ACTION = "com.fuying.sn.action.LOGCAT_START"; + public final static String LOGCAT_STOP_ACTION = "com.fuying.sn.action.LOGCAT_STOP"; private static final String TAG = "LogcatService"; + // 未下发配置直接 START 时的兜底参数,避免只采一行就结束 + private static final long DEFAULT_DURATION_SECONDS = 10 * 60L; + private static final long DEFAULT_FILE_MAX_SIZE = 10 * 1024 * 1024L; public LogcatService() { @@ -108,8 +113,8 @@ public class LogcatService extends BaseService { filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(LOGCAT_START_ACTION); filter.addAction(LOGCAT_STOP_ACTION); - // 保留原有跨应用 START/STOP 广播控制能力。 - ReceiverCompat.registerReceiver(this, receiver, filter, ReceiverCompat.RECEIVER_EXPORTED); + // 只接收本应用(含同 uid 的系统应用)发送的启停广播 + ReceiverCompat.registerReceiver(this, receiver, filter, ReceiverCompat.RECEIVER_NOT_EXPORTED); } /** @@ -145,8 +150,23 @@ public class LogcatService extends BaseService { Log.e(TAG, "startLogThread: already running"); return; } - session = new LogSession(logFilePath, start_Time, condition_duration, - condition_file_max_size, clear_file); + // 未下发配置时用兜底值;start_Time 为 0 时以当前时间为起点,避免立即超时 + long effectiveStartTime = start_Time; + if (effectiveStartTime <= 0) { + effectiveStartTime = System.currentTimeMillis() / 1000; + } + long effectiveDuration = condition_duration; + if (effectiveDuration <= 0) { + effectiveDuration = DEFAULT_DURATION_SECONDS; + } + long effectiveMaxSize = condition_file_max_size; + if (effectiveMaxSize <= 0) { + effectiveMaxSize = DEFAULT_FILE_MAX_SIZE; + } + Log.e(TAG, "startLogThread: startTime = " + effectiveStartTime + + " duration = " + effectiveDuration + " maxSize = " + effectiveMaxSize); + session = new LogSession(logFilePath, effectiveStartTime, effectiveDuration, + effectiveMaxSize, clear_file); mActiveSession = session; } // 每轮独立线程,上一轮尚未走完 finally 时也不会挡住新的 START @@ -287,9 +307,11 @@ public class LogcatService extends BaseService { break; } String logEntry = line + "\n"; - fileOutputStream.write(logEntry.getBytes()); + byte[] entryBytes = logEntry.getBytes(StandardCharsets.UTF_8); + fileOutputStream.write(entryBytes); fileOutputStream.flush(); - fileSize += logEntry.length(); + // 按真实字节数统计,中文等多字节字符不能用 String.length() + fileSize += entryBytes.length; if (fileSize >= session.maxFileSize || (session.startTime + session.duration) * 1000 < System.currentTimeMillis()) { session.running = false; diff --git a/app/src/main/java/com/fuying/sn/runtime/service/ManagerService.java b/app/src/main/java/com/fuying/sn/runtime/service/ManagerService.java index 1f29203..0e049f2 100644 --- a/app/src/main/java/com/fuying/sn/runtime/service/ManagerService.java +++ b/app/src/main/java/com/fuying/sn/runtime/service/ManagerService.java @@ -125,8 +125,9 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor registAppReceive(); registBootReceive(); setFloatingWindow(); - startEvent.throttleFirst(3, TimeUnit.HOURS) - .subscribe(timeObserver); + // 订阅句柄纳入 mDisposables,Service 销毁时统一释放 + mDisposables.add(startEvent.throttleFirst(3, TimeUnit.HOURS) + .subscribe(aLong -> timeObserver.onNext(aLong))); } @Override @@ -207,6 +208,11 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor // Log.e(TAG, "showFloatingWindow: debug mode skip"); // return; // } + // 已在屏时只刷新文案,避免每分钟 TIME_TICK 都做权限检查与 View 重建 + if (null != topView && topView.isAttachedToWindow()) { + initTopView(topView, name); + return; + } if (!Settings.canDrawOverlays(this)) { // 没有悬浮窗权限时原来会静默返回,出问题时完全无迹可查 Log.e(TAG, "showFloatingWindow: no overlay permission, skip. name=" + name); @@ -216,27 +222,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor if (null == windowManager) { windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); } - DisplayMetrics dm = new DisplayMetrics(); - windowManager.getDefaultDisplay().getRealMetrics(dm); - int width = dm.widthPixels; // 屏幕宽度(像素) - int height = dm.heightPixels; // 屏幕高度(像素) - // 新建悬浮窗控件 - final Button button = new Button(getApplicationContext()); - button.setText("霸屏测试"); - button.setAlpha(0.9f); - button.setBackgroundColor(Color.BLACK); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { -// windowManager.removeView(button); - } - }); if (null != topView) { - if (topView.isAttachedToWindow()) { - // 已在屏:只刷新文案,避免重复 addView - initTopView(topView, name); - return; - } // 引用还在但窗口已被系统移除(被其他窗口顶掉/系统回收): // 原实现会一直复用这个已不在屏上的 View,导致锁屏"看起来失效" Log.e(TAG, "showFloatingWindow: topView detached, rebuild it."); diff --git a/app/src/main/java/com/fuying/sn/runtime/sync/AppInventorySync.java b/app/src/main/java/com/fuying/sn/runtime/sync/AppInventorySync.java index 57bd15f..b3b8315 100644 --- a/app/src/main/java/com/fuying/sn/runtime/sync/AppInventorySync.java +++ b/app/src/main/java/com/fuying/sn/runtime/sync/AppInventorySync.java @@ -6,6 +6,7 @@ import android.annotation.SuppressLint; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; +import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; @@ -149,8 +150,12 @@ public final class AppInventorySync { Set showPkg = getShowPackages(); Log.e(TAG, "SendAppInstallInfo: showPkg: " + showPkg); for (PackageInfo info : list) { + // 直接用已查询到的 applicationInfo.flags 判断,避免每个包都去 PackageManager 查一次 + int appFlags = info.applicationInfo == null ? 0 : info.applicationInfo.flags; + boolean systemApp = (appFlags + & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; //排除掉部分系统应用 - if (ApkUtils.isSystemApp(mContext, info.packageName)) { + if (systemApp) { if (!showPkg.contains(info.packageName)) { continue; } @@ -302,7 +307,8 @@ public final class AppInventorySync { return appInfos; } }).subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()), new Observer>() { + // onNext 里要写 KVStore 和系统设置,属于 IO 操作,不能放主线程 + .observeOn(Schedulers.io()), new Observer>() { @Override public void onSubscribe(@NonNull Disposable d) { Log.e(TAG, "getAppWhiteList: onSubscribe: "); diff --git a/app/src/main/java/com/fuying/sn/runtime/sync/AppUsageReporter.java b/app/src/main/java/com/fuying/sn/runtime/sync/AppUsageReporter.java index afe3187..4b235d5 100644 --- a/app/src/main/java/com/fuying/sn/runtime/sync/AppUsageReporter.java +++ b/app/src/main/java/com/fuying/sn/runtime/sync/AppUsageReporter.java @@ -61,9 +61,14 @@ public final class AppUsageReporter { // return; } - String label = ApkUtils.getAppLable(mContext, packageName); - - repository.getAppUsageRecordObservable(packageName, label, openTime, closeTime) + // getAppLable 内部查询 PackageManager,不能在调用线程(管控主循环)同步执行 + final String[] labelHolder = new String[1]; + Observable.fromCallable(() -> ApkUtils.getAppLable(mContext, packageName)) + .subscribeOn(Schedulers.io()) + .flatMap(label -> { + labelHolder[0] = label; + return repository.getAppUsageRecordObservable(packageName, label, openTime, closeTime); + }) .to(BackgroundRequests.submit(new Observer() { @Override public void onSubscribe(@NonNull Disposable d) { @@ -78,14 +83,14 @@ public final class AppUsageReporter { return; } // 上传失败,保存到 Room,等网络恢复后重新上传 - saveAppUsageRecordToRoom(packageName, label, openTime, closeTime); + saveAppUsageRecordToRoom(packageName, labelHolder[0], openTime, closeTime); } @Override public void onError(@NonNull Throwable e) { Log.e(TAG, "sendAppUsageRecord: onError: " + e.getMessage()); // 上传失败,保存到 Room,等网络恢复后重新上传 - saveAppUsageRecordToRoom(packageName, label, openTime, closeTime); + saveAppUsageRecordToRoom(packageName, labelHolder[0], openTime, closeTime); onComplete(); } diff --git a/app/src/main/java/com/fuying/sn/runtime/sync/RemoteDiagnostics.java b/app/src/main/java/com/fuying/sn/runtime/sync/RemoteDiagnostics.java index e0c05aa..2ecf27b 100644 --- a/app/src/main/java/com/fuying/sn/runtime/sync/RemoteDiagnostics.java +++ b/app/src/main/java/com/fuying/sn/runtime/sync/RemoteDiagnostics.java @@ -184,6 +184,7 @@ public final class RemoteDiagnostics { } private static final int REQUEST_CODE = 12345; + private static final int STOP_REQUEST_CODE = 12346; public void getRunLog() { repository.getSnRunLogControl() @@ -204,24 +205,36 @@ public final class RemoteDiagnostics { LogcatService.setClearFile(snRunLog.getIs_clear()); long timestamp = snRunLog.getStart_time() * 1000; long nowTime = System.currentTimeMillis(); + long durationMillis = snRunLog.getDuration() * 1000; + if (durationMillis <= 0) { + // 时长为 0 时按 10 分钟兜底,否则 STOP 会立刻触发 + durationMillis = 10 * 60 * 1000L; + } AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); + long stopTime; if (nowTime > timestamp) { + // 配置的开始时间已过期,立即开始采集,结束时间要按当前时间重新起算 Intent intent = new Intent(LogcatService.LOGCAT_START_ACTION); + intent.setPackage(mContext.getPackageName()); mContext.sendBroadcast(intent); + stopTime = nowTime + durationMillis; } else { Intent intent = new Intent(LogcatService.LOGCAT_START_ACTION); + intent.setPackage(mContext.getPackageName()); PendingIntent startPendingIntent = PendingIntent.getBroadcast(mContext, REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timestamp, startPendingIntent); + stopTime = timestamp + durationMillis; } Intent intent = new Intent(LogcatService.LOGCAT_STOP_ACTION); + intent.setPackage(mContext.getPackageName()); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, - REQUEST_CODE, intent, + STOP_REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, - timestamp + snRunLog.getDuration() * 1000, pendingIntent); + stopTime, pendingIntent); } }