fix: 修复缓存落盘、线程切换与后台服务健壮性问题
- 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
This commit is contained in:
1 parent
2bfcb80dc5
commit
1a2525176a
14 files changed
+359
-120
No files matched your search
@@ -154,7 +154,6 @@
|
||||
<intent-filter android:priority="1000">
|
||||
<action android:name="zuoyeos.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.BATTERY_LEVEL_CHANGED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver
|
||||
|
||||
@@ -118,12 +118,31 @@ public class CacheHelper {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存目录打开失败时 mDiskLruCache 为 null,所有读写入口先做一次判空,
|
||||
* 避免直接触发空指针把调用方链路打断。
|
||||
*/
|
||||
private boolean ensureAvailable() {
|
||||
if (mDiskLruCache == null) {
|
||||
Log.e(TAG, "ensureAvailable: mDiskLruCache is null");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// =======================================
|
||||
// ============== String 数据 读写 =============
|
||||
// =======================================
|
||||
|
||||
public void put(String key, String value) {
|
||||
Log.e(TAG, "put: key = " + key + " value = " + value);
|
||||
Log.e(TAG, "put: key = " + key + " valueLength = " + (value == null ? 0 : value.length()));
|
||||
if (value == null) {
|
||||
Log.e(TAG, "put: value is null");
|
||||
return;
|
||||
}
|
||||
if (!ensureAvailable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DiskLruCache.Editor edit = null;
|
||||
BufferedWriter bw = null;
|
||||
@@ -135,17 +154,27 @@ public class CacheHelper {
|
||||
OutputStream os = edit.newOutputStream(0);
|
||||
bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
|
||||
bw.write(value);
|
||||
// 先把内容刷到磁盘并关闭流,再提交,否则 commit 时内容可能还没落盘
|
||||
bw.flush();
|
||||
bw.close();
|
||||
bw = null;
|
||||
edit.commit();//write CLEAN
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "put: " + e.getMessage(), e);
|
||||
Log.e(TAG, "put: " + e.getMessage());
|
||||
try {
|
||||
if (bw != null) {
|
||||
bw.close();
|
||||
bw = null;
|
||||
}
|
||||
} catch (IOException e1) {
|
||||
Log.e(TAG, "put: " + e1.getMessage(), e1);
|
||||
}
|
||||
try {
|
||||
if (edit != null) {
|
||||
edit.abort();//write REMOVE
|
||||
}
|
||||
} catch (IOException e1) {
|
||||
Log.e(TAG, "put: " + e1.getMessage(), e1);
|
||||
Log.e(TAG, "put: " + e1.getMessage());
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
@@ -154,21 +183,24 @@ public class CacheHelper {
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "put: " + e.getMessage(), e);
|
||||
Log.e(TAG, "put: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getAsString(String key) {
|
||||
Log.e(TAG, "getAsString: " + key);
|
||||
if (!ensureAvailable()) {
|
||||
return null;
|
||||
}
|
||||
InputStream inputStream = null;
|
||||
InputStreamReader isr = null;
|
||||
try {
|
||||
inputStream = get(key);
|
||||
if (inputStream == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
char[] buf = new char[1024];
|
||||
int len;
|
||||
while ((len = isr.read(buf)) != -1) {
|
||||
@@ -177,8 +209,14 @@ public class CacheHelper {
|
||||
return sb.toString();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "getAsString: " + e.getMessage(), e);
|
||||
Log.e(TAG, "getAsString: " + e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
if (isr != null) {
|
||||
isr.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "getAsString: " + e.getMessage(), e);
|
||||
}
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
@@ -392,6 +430,9 @@ public class CacheHelper {
|
||||
// ============= other methods =============
|
||||
// =======================================
|
||||
public boolean remove(String key) {
|
||||
if (!ensureAvailable()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
String hashKey = DiskCacheUtils.hashKeyForDisk(key);
|
||||
return mDiskLruCache.remove(hashKey);
|
||||
@@ -402,34 +443,58 @@ public class CacheHelper {
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
if (!ensureAvailable()) {
|
||||
return;
|
||||
}
|
||||
mDiskLruCache.close();
|
||||
}
|
||||
|
||||
public void delete() throws IOException {
|
||||
if (!ensureAvailable()) {
|
||||
return;
|
||||
}
|
||||
mDiskLruCache.delete();
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
if (!ensureAvailable()) {
|
||||
return;
|
||||
}
|
||||
mDiskLruCache.flush();
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
if (!ensureAvailable()) {
|
||||
return true;
|
||||
}
|
||||
return mDiskLruCache.isClosed();
|
||||
}
|
||||
|
||||
public long size() {
|
||||
if (!ensureAvailable()) {
|
||||
return 0L;
|
||||
}
|
||||
return mDiskLruCache.size();
|
||||
}
|
||||
|
||||
public void setMaxSize(long maxSize) {
|
||||
if (!ensureAvailable()) {
|
||||
return;
|
||||
}
|
||||
mDiskLruCache.setMaxSize(maxSize);
|
||||
}
|
||||
|
||||
public File getDirectory() {
|
||||
if (!ensureAvailable()) {
|
||||
return null;
|
||||
}
|
||||
return mDiskLruCache.getDirectory();
|
||||
}
|
||||
|
||||
public long getMaxSize() {
|
||||
if (!ensureAvailable()) {
|
||||
return 0L;
|
||||
}
|
||||
return mDiskLruCache.getMaxSize();
|
||||
}
|
||||
|
||||
@@ -439,6 +504,9 @@ public class CacheHelper {
|
||||
// =======================================
|
||||
//basic editor
|
||||
public DiskLruCache.Editor editor(String key) {
|
||||
if (!ensureAvailable()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String hashKey = DiskCacheUtils.hashKeyForDisk(key);
|
||||
//wirte DIRTY
|
||||
@@ -450,7 +518,6 @@ public class CacheHelper {
|
||||
return edit;
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "editor: " + e.getMessage(), e);
|
||||
Log.e(TAG, "editor: " + e.getMessage());
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -459,6 +526,9 @@ public class CacheHelper {
|
||||
|
||||
//basic get
|
||||
public InputStream get(String key) {
|
||||
if (!ensureAvailable()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(DiskCacheUtils.hashKeyForDisk(key));
|
||||
if (snapshot == null) //not find entry , or entry.readable = false
|
||||
|
||||
@@ -156,18 +156,24 @@ public final class DeviceRepository {
|
||||
Observable<T> 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 {
|
||||
<T> Observable<BaseResponse<T>> withMultiLevelCache(
|
||||
Observable<BaseResponse<T>> network, String key, Type type, long ttlMillis) {
|
||||
return scheduleForCache(key, Observable.defer(() -> {
|
||||
synchronized (CACHE_LOCK) {
|
||||
BaseResponse<T> fresh = CACHE_MANAGER.getCache(key);
|
||||
if (fresh != null) {
|
||||
return Observable.just(fresh);
|
||||
}
|
||||
BaseResponse<T> stale = readDisk(key, type);
|
||||
Observable<BaseResponse<T>> refresh = Observable.defer(() -> {
|
||||
synchronized (CACHE_LOCK) {
|
||||
// 发出磁盘数据后再次检查内存,复用其他订阅刚刷新的结果。
|
||||
BaseResponse<T> 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<T> fresh = CACHE_MANAGER.getCache(key);
|
||||
if (fresh != null) {
|
||||
return Observable.just(fresh);
|
||||
}
|
||||
// 磁盘读取是真正的 IO,不能放在 CACHE_LOCK 内阻塞其他缓存的读写
|
||||
BaseResponse<T> stale = readDisk(key, type);
|
||||
Observable<BaseResponse<T>> refresh = Observable.defer(() -> {
|
||||
synchronized (CACHE_LOCK) {
|
||||
// 发出磁盘数据后再次检查内存,复用其他订阅刚刷新的结果。
|
||||
BaseResponse<T> 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);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<String> 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<ApplicationInfo> apps = mPackageManager.getInstalledApplications(0);
|
||||
Set<String> 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<AppTimeControlInfo> 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<AppTimeControlInfo> list) {
|
||||
// 配置已更新,启动时的 Room 恢复结果即使稍后返回也应丢弃
|
||||
mConfigVersion++;
|
||||
rebuildAppMaps(list);
|
||||
// 新配置下发后,用当日配额刷新 Room 剩余时长表
|
||||
saveAllRemainingToDb();
|
||||
}
|
||||
|
||||
// --- 广播监听 ---
|
||||
|
||||
// 跟随 Application 常驻,进程退出由系统回收;显式销毁时使用同一实例注销。
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.");
|
||||
|
||||
@@ -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<String> 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<HashSet<AppInfo>>() {
|
||||
// onNext 里要写 KVStore 和系统设置,属于 IO 操作,不能放主线程
|
||||
.observeOn(Schedulers.io()), new Observer<HashSet<AppInfo>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
Log.e(TAG, "getAppWhiteList: onSubscribe: ");
|
||||
|
||||
@@ -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<BaseResponse>() {
|
||||
@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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user