refactor: 优化数据层、缓存与后台服务
- 日志库迁移 Room,读写串行化并保留 7 天记录 - 时间配置拆分 MMKV/Room 读取,写库异步化 - RxCacheManager 增加 200 条容量上限 - LogcatService 修复停止与上传时序 - BootReceiver 广播声明收敛为实际处理的 3 个 action - release 变体移除 debuggable - 开启 Gradle 并行与构建缓存 - 删除未使用的 activity_guide 布局
This commit is contained in:
1 parent
5f8d192b4e
commit
6712fbdb75
25 files changed
+638
-371
No files matched your search
@@ -14,8 +14,6 @@
|
||||
<uses-permission android:name="android.permission.SET_ACTIVITY_WATCHER" />
|
||||
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.ACTION_SCREEN_ON" />
|
||||
<uses-permission android:name="android.permission.ACTION_SCREEN_OFF" />
|
||||
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
|
||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
|
||||
@@ -154,18 +152,9 @@
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<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_CHANGED" />
|
||||
<action android:name="android.intent.action.BATTERY_LEVEL_CHANGED" />
|
||||
<action android:name="android.intent.action.BATTERY_LOW" />
|
||||
<action android:name="android.intent.action.BATTERY_OKAY" />
|
||||
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
|
||||
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
|
||||
<action android:name="android.intent.action.DATE_CHANGED" />
|
||||
<action android:name="android.intent.action.TIME_TICK" />
|
||||
<action android:name="android.intent.action.USER_PRESENT" />
|
||||
<action android:name="android.intent.action.SCREEN_ON" />
|
||||
<action android:name="android.intent.action.SCREEN_OFF" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver
|
||||
|
||||
@@ -45,4 +45,8 @@ public class CacheEntry<T> {
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public long getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,37 @@ public class CacheHelper {
|
||||
private static final String TAG = "DiskLruCacheHelper";
|
||||
|
||||
private static final String DIR_NAME = "diskCache";
|
||||
private static final int MAX_COUNT = 1024 * 1024 * 1024;
|
||||
private static final int MAX_COUNT = 16 * 1024 * 1024;
|
||||
private static final int DEFAULT_APP_VERSION = 1;
|
||||
|
||||
/**
|
||||
* 默认目录只允许一个实例:DiskLruCache 不支持同一目录被多个实例同时打开。
|
||||
*/
|
||||
private static volatile CacheHelper sInstance;
|
||||
|
||||
private DiskLruCache mDiskLruCache;
|
||||
|
||||
public CacheHelper(Context context) {
|
||||
private CacheHelper(Context context) {
|
||||
mDiskLruCache = generateCache(context, DIR_NAME, MAX_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认磁盘缓存的全局唯一实例。
|
||||
*
|
||||
* @param context 任意上下文,内部只使用应用级路径
|
||||
* @return 默认目录的缓存实例
|
||||
*/
|
||||
public static CacheHelper getInstance(Context context) {
|
||||
if (sInstance == null) {
|
||||
synchronized (CacheHelper.class) {
|
||||
if (sInstance == null) {
|
||||
sInstance = new CacheHelper(context.getApplicationContext());
|
||||
}
|
||||
}
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
public CacheHelper(Context context, String dirName) {
|
||||
mDiskLruCache = generateCache(context, dirName, MAX_COUNT);
|
||||
}
|
||||
|
||||
@@ -2,12 +2,20 @@ package com.fuying.sn.core.data.local.cache;
|
||||
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 全局缓存管理器:线程安全,存储所有接口缓存
|
||||
* 全局缓存管理器:线程安全,存储所有接口缓存。
|
||||
* 缓存条目有容量上限,写入超出后先清过期项,再从最旧的开始淘汰,避免长期运行无限增长。
|
||||
*/
|
||||
public class RxCacheManager {
|
||||
// 缓存条目上限,接口缓存 key 数量有限,200 条足够覆盖正常使用
|
||||
private static final int MAX_CACHE_COUNT = 200;
|
||||
|
||||
// 单例
|
||||
private static volatile RxCacheManager INSTANCE;
|
||||
// 缓存容器:key=请求唯一标识,value=缓存实体
|
||||
@@ -35,6 +43,7 @@ public class RxCacheManager {
|
||||
if (key == null || data == null) return;
|
||||
cacheMap.put(key, new CacheEntry<>(data, System.currentTimeMillis(),
|
||||
SystemClock.elapsedRealtime(), expireTimeMillis));
|
||||
trimIfNeeded();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,8 +52,10 @@ public class RxCacheManager {
|
||||
public <T> T getCache(String key) {
|
||||
CacheEntry<?> entry = cacheMap.get(key);
|
||||
if (entry == null || entry.isExpired()) {
|
||||
// 缓存不存在/已过期,移除并返回null
|
||||
cacheMap.remove(key);
|
||||
// 缓存不存在/已过期,移除并返回null;按 value 移除,避免误删并发写入的新条目
|
||||
if (entry != null) {
|
||||
cacheMap.remove(key, entry);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return (T) entry.getData();
|
||||
@@ -63,4 +74,29 @@ public class RxCacheManager {
|
||||
public void removeCache(String key) {
|
||||
cacheMap.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 容量超限时回收:先清理已过期条目,仍超限则淘汰创建时间最早的条目
|
||||
*/
|
||||
private void trimIfNeeded() {
|
||||
if (cacheMap.size() <= MAX_CACHE_COUNT) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, CacheEntry<?>> entry : cacheMap.entrySet()) {
|
||||
if (entry.getValue().isExpired()) {
|
||||
cacheMap.remove(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
int overflow = cacheMap.size() - MAX_CACHE_COUNT;
|
||||
if (overflow <= 0) {
|
||||
return;
|
||||
}
|
||||
List<Map.Entry<String, CacheEntry<?>>> entries = new ArrayList<>(cacheMap.entrySet());
|
||||
Collections.sort(entries, (left, right) ->
|
||||
Long.compare(left.getValue().getCreateTime(), right.getValue().getCreateTime()));
|
||||
for (int i = 0; i < overflow && i < entries.size(); i++) {
|
||||
Map.Entry<String, CacheEntry<?>> entry = entries.get(i);
|
||||
cacheMap.remove(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.fuying.sn.core.data.local.db.log;
|
||||
|
||||
import android.content.Context;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
import android.os.Environment;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class LogDBHelper extends SQLiteOpenHelper {
|
||||
public static final String DATABASE_NAME = "requestlog.db";
|
||||
private static final String DATABASE_FILE_NAME = Environment.getExternalStorageDirectory().getPath() + File.separator + DATABASE_NAME;
|
||||
private static final int DATABASE_VERSION = 1;
|
||||
|
||||
public LogDBHelper(Context context) {
|
||||
super(context, DATABASE_FILE_NAME, null, DATABASE_VERSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(SQLiteDatabase sqLiteDatabase) {
|
||||
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS logtable (" +
|
||||
"id integer primary key autoincrement," +
|
||||
"code varchar(8)," +
|
||||
"timestamp integer," +
|
||||
"event varchar(64)," +
|
||||
"operate varchar(64)," +
|
||||
"content text" +
|
||||
")"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
package com.fuying.sn.core.data.local.db.log;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
|
||||
@@ -20,23 +17,40 @@ import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* 运行日志管理器。
|
||||
* 底层由 Room 承载,所有读写都在单线程队列中串行执行,避免阻塞主线程和广播回调。
|
||||
*/
|
||||
public class LogDBManager {
|
||||
private static String TAG = "LogDBManager";
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private static LogDBManager sInstance;
|
||||
private Context mContext;
|
||||
private LogDBHelper mDBHelper;
|
||||
private final Context mContext;
|
||||
private final LogDao mLogDao;
|
||||
private final ExecutorService mExecutor;
|
||||
|
||||
private static final String TABLE_NAME = "logtable";
|
||||
private static final String LOG_CODE_REBOOT = "1001";
|
||||
private static final String LOG_CODE_NETWORK = "1002";
|
||||
private static final String LOG_CODE_NETCHANGE = "1003";
|
||||
|
||||
private static final String LOG_EVENT_REBOOT = "设备重启";
|
||||
private static final String LOG_EVENT_NETWORK = "首次联网";
|
||||
private static final String LOG_EVENT_NETCHANGE = "网络改变";
|
||||
public static final String LOG_EVENT_BATTERY = "充电改变";
|
||||
|
||||
private LogDBManager(Context context) {
|
||||
if (context == null) {
|
||||
throw new RuntimeException("Context is NULL");
|
||||
}
|
||||
mContext = context;
|
||||
mDBHelper = new LogDBHelper(context);
|
||||
mContext = context.getApplicationContext();
|
||||
mLogDao = LogDatabase.getInstance(mContext).logDao();
|
||||
mExecutor = Executors.newSingleThreadExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable, "log-db");
|
||||
thread.setPriority(Thread.MIN_PRIORITY);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
public static void init(Context context) {
|
||||
@@ -52,22 +66,6 @@ public class LogDBManager {
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
public LogDBHelper getDBHelper() {
|
||||
if (mDBHelper == null) {
|
||||
mDBHelper = new LogDBHelper(mContext);
|
||||
}
|
||||
return mDBHelper;
|
||||
}
|
||||
|
||||
private static final String LOG_CODE_REBOOT = "1001";
|
||||
private static final String LOG_CODE_NETWORK = "1002";
|
||||
private static final String LOG_CODE_NETCHANGE = "1003";
|
||||
|
||||
private static final String LOG_EVENT_REBOOT = "设备重启";
|
||||
private static final String LOG_EVENT_NETWORK = "首次联网";
|
||||
private static final String LOG_EVENT_NETCHANGE = "网络改变";
|
||||
public static final String LOG_EVENT_BATTERY = "充电改变";
|
||||
|
||||
public void creatRebootLog(String operate, String content) {
|
||||
LogBean logBean = new LogBean();
|
||||
logBean.setCode(LOG_CODE_REBOOT);
|
||||
@@ -108,68 +106,57 @@ public class LogDBManager {
|
||||
saveLog(logBean);
|
||||
}
|
||||
|
||||
|
||||
public void saveLog(LogBean logBean) {
|
||||
SQLiteDatabase db = mDBHelper.getWritableDatabase();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put("code", logBean.getCode());
|
||||
values.put("timestamp", logBean.getTimestamp());
|
||||
values.put("event", logBean.getEvent());
|
||||
values.put("operate", logBean.getOperate());
|
||||
values.put("content", logBean.getContent());
|
||||
db.insert(TABLE_NAME, null, values);
|
||||
if (logBean == null) {
|
||||
return;
|
||||
}
|
||||
LogEntity entity = toEntity(logBean);
|
||||
execute("saveLog", () -> {
|
||||
mLogDao.insert(entity);
|
||||
// 只保留最近一周,避免日志表随运行时间无限增长
|
||||
mLogDao.deleteBefore(System.currentTimeMillis() - RETENTION_MILLIS);
|
||||
});
|
||||
}
|
||||
|
||||
public void delete(Integer id) {
|
||||
SQLiteDatabase db = mDBHelper.getWritableDatabase();
|
||||
db.delete(TABLE_NAME, "id=?", new String[]{id.toString()});
|
||||
if (id == null) {
|
||||
return;
|
||||
}
|
||||
long rowId = id;
|
||||
execute("delete", () -> mLogDao.deleteById(rowId));
|
||||
}
|
||||
|
||||
public void deleteAll() {
|
||||
SQLiteDatabase db = mDBHelper.getWritableDatabase();
|
||||
db.delete(TABLE_NAME, "", null);
|
||||
execute("deleteAll", mLogDao::deleteAll);
|
||||
}
|
||||
|
||||
public void update(LogBean logBean) {
|
||||
SQLiteDatabase db = mDBHelper.getWritableDatabase();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put("code", logBean.getCode());
|
||||
values.put("timestamp", logBean.getTimestamp());
|
||||
values.put("event", logBean.getEvent());
|
||||
values.put("operate", logBean.getOperate());
|
||||
values.put("content", logBean.getContent());
|
||||
db.update(TABLE_NAME, values, "id=?", new String[]{logBean.getId().toString()});
|
||||
if (logBean == null || logBean.getId() == null) {
|
||||
return;
|
||||
}
|
||||
LogEntity entity = toEntity(logBean);
|
||||
execute("update", () -> mLogDao.update(entity));
|
||||
}
|
||||
|
||||
private long aWeekDayTime = 1000 * 60 * 60 * 24 * 7;
|
||||
private static final long RETENTION_MILLIS = 1000 * 60 * 60 * 24 * 7;
|
||||
|
||||
public List<LogBean> getLogList() {
|
||||
List<LogBean> logBeanList = new ArrayList<>();
|
||||
SQLiteDatabase db = mDBHelper.getReadableDatabase();
|
||||
long time = System.currentTimeMillis() - aWeekDayTime;
|
||||
String sql = "select * from " + TABLE_NAME + " where" + " timestamp > " + time;
|
||||
Cursor cursor = null;
|
||||
try {
|
||||
cursor = db.rawQuery(sql, null);
|
||||
while (cursor.moveToNext()) {
|
||||
LogBean logBean = new LogBean();
|
||||
logBean.setId(cursor.getInt(cursor.getColumnIndex("id")));
|
||||
logBean.setCode(cursor.getString(cursor.getColumnIndex("code")));
|
||||
logBean.setTimestamp(cursor.getLong(cursor.getColumnIndex("timestamp")));
|
||||
logBean.setEvent(cursor.getString(cursor.getColumnIndex("event")));
|
||||
logBean.setOperate(cursor.getString(cursor.getColumnIndex("operate")));
|
||||
logBean.setContent(cursor.getString(cursor.getColumnIndex("content")));
|
||||
logBeanList.add(logBean);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return mExecutor.submit(() -> {
|
||||
List<LogEntity> entities = mLogDao.querySince(System.currentTimeMillis() - RETENTION_MILLIS);
|
||||
List<LogBean> logBeanList = new ArrayList<>(entities.size());
|
||||
for (LogEntity entity : entities) {
|
||||
logBeanList.add(toBean(entity));
|
||||
}
|
||||
return logBeanList;
|
||||
}).get();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.e(TAG, "getLogList: " + e.getMessage(), e);
|
||||
} catch (ExecutionException e) {
|
||||
Log.e(TAG, "getLogList: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (cursor != null) {
|
||||
cursor.close();
|
||||
}
|
||||
db.close();
|
||||
}
|
||||
return logBeanList;
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
public String saveToFile() {
|
||||
@@ -205,4 +192,37 @@ public class LogDBManager {
|
||||
return logFile.getAbsolutePath();
|
||||
}
|
||||
|
||||
private void execute(String method, Runnable task) {
|
||||
mExecutor.execute(() -> {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, method + ": " + e.getMessage(), e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static LogEntity toEntity(LogBean logBean) {
|
||||
LogEntity entity = new LogEntity();
|
||||
if (logBean.getId() != null) {
|
||||
entity.id = logBean.getId();
|
||||
}
|
||||
entity.code = logBean.getCode();
|
||||
entity.timestamp = logBean.getTimestamp();
|
||||
entity.event = logBean.getEvent();
|
||||
entity.operate = logBean.getOperate();
|
||||
entity.content = logBean.getContent();
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static LogBean toBean(LogEntity entity) {
|
||||
LogBean logBean = new LogBean();
|
||||
logBean.setId((int) entity.id);
|
||||
logBean.setCode(entity.code);
|
||||
logBean.setTimestamp(entity.timestamp);
|
||||
logBean.setEvent(entity.event);
|
||||
logBean.setOperate(entity.operate);
|
||||
logBean.setContent(entity.content);
|
||||
return logBean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.fuying.sn.core.data.local.db.log;
|
||||
|
||||
import androidx.room.Dao;
|
||||
import androidx.room.Insert;
|
||||
import androidx.room.Query;
|
||||
import androidx.room.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 运行日志的 DAO。
|
||||
* 日志量小且只保留最近一周,按写入顺序返回即可。
|
||||
*/
|
||||
@Dao
|
||||
public interface LogDao {
|
||||
|
||||
@Insert
|
||||
long insert(LogEntity entity);
|
||||
|
||||
@Update
|
||||
void update(LogEntity entity);
|
||||
|
||||
@Query("DELETE FROM logtable WHERE id = :id")
|
||||
void deleteById(long id);
|
||||
|
||||
@Query("DELETE FROM logtable")
|
||||
void deleteAll();
|
||||
|
||||
@Query("DELETE FROM logtable WHERE timestamp < :before")
|
||||
void deleteBefore(long before);
|
||||
|
||||
@Query("SELECT * FROM logtable WHERE timestamp > :since ORDER BY id ASC")
|
||||
List<LogEntity> querySince(long since);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.fuying.sn.core.data.local.db.log;
|
||||
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.room.Database;
|
||||
import androidx.room.Room;
|
||||
import androidx.room.RoomDatabase;
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 运行日志数据库(Room)。
|
||||
* 数据库文件从外部存储迁移到应用私有目录,首次创建时导入旧的 requestlog.db。
|
||||
*/
|
||||
@Database(
|
||||
entities = {LogEntity.class},
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
public abstract class LogDatabase extends RoomDatabase {
|
||||
|
||||
private static final String TAG = "LogDatabase";
|
||||
|
||||
/** 旧版数据库文件名,位于外部存储根目录 */
|
||||
private static final String LEGACY_DB_NAME = "requestlog.db";
|
||||
|
||||
private static volatile LogDatabase sInstance;
|
||||
|
||||
public abstract LogDao logDao();
|
||||
|
||||
public static LogDatabase getInstance(Context context) {
|
||||
if (sInstance == null) {
|
||||
synchronized (LogDatabase.class) {
|
||||
if (sInstance == null) {
|
||||
sInstance = Room.databaseBuilder(context.getApplicationContext(),
|
||||
LogDatabase.class, LEGACY_DB_NAME)
|
||||
.fallbackToDestructiveMigration()
|
||||
.addCallback(new Callback() {
|
||||
@Override
|
||||
public void onCreate(@NonNull SupportSQLiteDatabase db) {
|
||||
super.onCreate(db);
|
||||
importLegacyLogs(db);
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次性导入旧库日志。
|
||||
* 旧库可能不存在或无读取权限,失败时保留原文件,不影响新库使用。
|
||||
*/
|
||||
private static void importLegacyLogs(SupportSQLiteDatabase db) {
|
||||
File legacyFile = new File(Environment.getExternalStorageDirectory(), LEGACY_DB_NAME);
|
||||
if (!legacyFile.exists()) {
|
||||
return;
|
||||
}
|
||||
SQLiteDatabase legacyDb = null;
|
||||
Cursor cursor = null;
|
||||
boolean imported = true;
|
||||
try {
|
||||
legacyDb = SQLiteDatabase.openDatabase(legacyFile.getAbsolutePath(), null,
|
||||
SQLiteDatabase.OPEN_READONLY);
|
||||
cursor = legacyDb.rawQuery(
|
||||
"SELECT code, timestamp, event, operate, content FROM logtable", null);
|
||||
while (cursor.moveToNext()) {
|
||||
ContentValues values = new ContentValues();
|
||||
values.put("code", cursor.getString(0));
|
||||
values.put("timestamp", cursor.getLong(1));
|
||||
values.put("event", cursor.getString(2));
|
||||
values.put("operate", cursor.getString(3));
|
||||
values.put("content", cursor.getString(4));
|
||||
db.insert("logtable", SQLiteDatabase.CONFLICT_IGNORE, values);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
imported = false;
|
||||
Log.e(TAG, "importLegacyLogs: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (cursor != null) {
|
||||
cursor.close();
|
||||
}
|
||||
if (legacyDb != null) {
|
||||
legacyDb.close();
|
||||
}
|
||||
}
|
||||
if (imported) {
|
||||
// 导入成功后删除旧库及其临时文件,避免每次安装都残留在外部存储
|
||||
legacyFile.delete();
|
||||
new File(legacyFile.getPath() + "-wal").delete();
|
||||
new File(legacyFile.getPath() + "-shm").delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.fuying.sn.core.data.local.db.log;
|
||||
|
||||
import androidx.room.Entity;
|
||||
import androidx.room.Index;
|
||||
import androidx.room.PrimaryKey;
|
||||
|
||||
/**
|
||||
* 运行日志实体(Room)。
|
||||
* 字段与旧版 requestlog.db 的 logtable 保持一致,便于迁移历史数据。
|
||||
*/
|
||||
@Entity(tableName = "logtable", indices = {@Index("timestamp")})
|
||||
public class LogEntity {
|
||||
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
public long id;
|
||||
|
||||
public String code;
|
||||
|
||||
public Long timestamp;
|
||||
|
||||
public String event;
|
||||
|
||||
public String operate;
|
||||
|
||||
public String content;
|
||||
}
|
||||
@@ -27,7 +27,6 @@ public abstract class AppUsageRecordDatabase extends RoomDatabase {
|
||||
if (sInstance == null) {
|
||||
sInstance = Room.databaseBuilder(context.getApplicationContext(),
|
||||
AppUsageRecordDatabase.class, "app_usage_record.db")
|
||||
.allowMainThreadQueries()
|
||||
.fallbackToDestructiveMigration()
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 时间管控相关数据的 DAO。
|
||||
* 同步方法用于低频/启动恢复,异步(RxJava)方法用于高频剩余时长更新。
|
||||
* 全部为同步方法,统一由 Repository 在后台调度器上调用,禁止在主线程直接访问。
|
||||
*/
|
||||
@Dao
|
||||
public interface TimeControlDao {
|
||||
@@ -37,9 +37,6 @@ public interface TimeControlDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
void insertRemaining(AppRemainingEntity entity);
|
||||
|
||||
@Query("UPDATE app_remaining_time SET remaining_seconds = :remaining, updated_at = :updatedAt WHERE app_package = :pkg")
|
||||
void updateRemaining(String pkg, long remaining, long updatedAt);
|
||||
|
||||
@Query("DELETE FROM app_remaining_time")
|
||||
void clearRemaining();
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ public abstract class TimeControlDatabase extends RoomDatabase {
|
||||
if (sInstance == null) {
|
||||
sInstance = Room.databaseBuilder(context.getApplicationContext(),
|
||||
TimeControlDatabase.class, "time_control.db")
|
||||
.allowMainThreadQueries()
|
||||
.fallbackToDestructiveMigration()
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import retrofit2.converter.gson.GsonConverterFactory;
|
||||
*/
|
||||
public final class OkHttpManager {
|
||||
private static final int TIME_OUT = 30;
|
||||
private static final long CACHE_SIZE = 64L * 1024 * 1024;
|
||||
private static final long CACHE_SIZE = 16L * 1024 * 1024;
|
||||
|
||||
private final OkHttpClient client;
|
||||
private final Retrofit retrofit;
|
||||
|
||||
@@ -25,6 +25,7 @@ import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import io.reactivex.rxjava3.core.Scheduler;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
|
||||
/**
|
||||
@@ -54,12 +55,17 @@ public class TimeConfigRepository {
|
||||
private static final long RETRY_INTERVAL = 60; // 重试间隔(秒)
|
||||
private static final int MAX_RETRY_COUNT = 10; // 最大重试次数,超过后停止重试
|
||||
|
||||
/**
|
||||
* 数据库写调度器:单线程保证 clear + insert 等组合操作的提交顺序。
|
||||
*/
|
||||
private static final Scheduler DB_WRITE_SCHEDULER = Schedulers.single();
|
||||
|
||||
private final Gson mGson = new Gson();
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private static volatile TimeConfigRepository sInstance;
|
||||
|
||||
private final TimeControlDatabase mDb;
|
||||
private final TimeControlDao mDao;
|
||||
|
||||
private SnTimeControlInfo mSnTimeControlInfo;
|
||||
@@ -69,7 +75,8 @@ public class TimeConfigRepository {
|
||||
private boolean mAppControlFetched = false;
|
||||
|
||||
private TimeConfigRepository(Context context) {
|
||||
this.mDao = TimeControlDatabase.getInstance(context).timeControlDao();
|
||||
this.mDb = TimeControlDatabase.getInstance(context);
|
||||
this.mDao = mDb.timeControlDao();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,9 +157,10 @@ public class TimeConfigRepository {
|
||||
// --- 本地缓存(离线可用性) ---
|
||||
|
||||
/**
|
||||
* 从 MMKV 加载两级配置缓存,保证网络不可用时设备仍有配置可管控。
|
||||
* 从 MMKV 加载配置缓存,保证网络不可用时设备仍有配置可管控。
|
||||
* 只读 MMKV,可在主线程调用;Room 中的最新数据由 {@link #loadPersistedConfig()} 异步覆盖。
|
||||
*/
|
||||
public void loadLocalConfig() {
|
||||
public void loadCacheConfig() {
|
||||
// 从 MMKV 恢复设备(SN)信息缓存,保证离线可用
|
||||
String snInfoJson = KVStore.decodeString(SN_INFO, "");
|
||||
if (!TextUtils.isEmpty(snInfoJson)) {
|
||||
@@ -178,22 +186,7 @@ public class TimeConfigRepository {
|
||||
}
|
||||
}
|
||||
|
||||
// App 配置优先从 Room 恢复(重启后立即可用,不依赖"上次是否成功拉取过")
|
||||
List<AppTimeControlEntity> controlEntities = mDao.getAllControls();
|
||||
if (controlEntities != null && !controlEntities.isEmpty()) {
|
||||
mAppTimeControlList = new ArrayList<>();
|
||||
for (AppTimeControlEntity entity : controlEntities) {
|
||||
if (TextUtils.isEmpty(entity.app_package)) continue; // 防御空包名
|
||||
AppTimeControlInfo info = toInfo(entity);
|
||||
if (info != null) {
|
||||
mAppTimeControlList.add(info);
|
||||
}
|
||||
}
|
||||
Log.e(TAG, "Loaded App config from Room, size=" + mAppTimeControlList.size());
|
||||
return; // Room 有数据则优先,MMKV 仅作兜底
|
||||
}
|
||||
|
||||
// Room 无数据时,退回 MMKV 缓存
|
||||
// App 配置先以 MMKV 作为兜底,Room 数据由 loadPersistedConfig 异步覆盖
|
||||
String appJson = KVStore.decodeString(APP_TIME_CONTROL_INFO, "");
|
||||
if (!TextUtils.isEmpty(appJson)) {
|
||||
try {
|
||||
@@ -207,6 +200,36 @@ public class TimeConfigRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Room 读取 App 管控配置与已扣减剩余时长,在 IO 线程执行。
|
||||
* Room 无 App 配置时返回空列表,调用方可继续使用 MMKV 兜底数据。
|
||||
*/
|
||||
public Observable<PersistedConfig> loadPersistedConfig() {
|
||||
return Observable.fromCallable(() -> {
|
||||
List<AppTimeControlInfo> controls = new ArrayList<>();
|
||||
List<AppTimeControlEntity> controlEntities = mDao.getAllControls();
|
||||
if (controlEntities != null) {
|
||||
for (AppTimeControlEntity entity : controlEntities) {
|
||||
if (TextUtils.isEmpty(entity.app_package)) continue; // 防御空包名
|
||||
AppTimeControlInfo info = toInfo(entity);
|
||||
if (info != null) {
|
||||
controls.add(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!controls.isEmpty()) {
|
||||
mAppTimeControlList = controls;
|
||||
Log.e(TAG, "Loaded App config from Room, size=" + controls.size());
|
||||
}
|
||||
|
||||
List<AppRemainingEntity> remaining = mDao.getAllRemaining();
|
||||
if (remaining == null) {
|
||||
remaining = new ArrayList<>();
|
||||
}
|
||||
return new PersistedConfig(controls, remaining);
|
||||
}).subscribeOn(Schedulers.io());
|
||||
}
|
||||
|
||||
// --- 网络拉取 + 重试 ---
|
||||
|
||||
/**
|
||||
@@ -382,62 +405,64 @@ public class TimeConfigRepository {
|
||||
// --- Room:App 管控配置持久化 ---
|
||||
|
||||
/**
|
||||
* 将最新 App 管控配置整体替换写入 Room(低频操作,主线程可接受)。
|
||||
* 将最新 App 管控配置整体替换写入 Room。
|
||||
* 写库在单线程调度器上异步执行,并在事务内完成 clear + insert。
|
||||
*/
|
||||
private void saveAppControlsToDb(List<AppTimeControlInfo> list) {
|
||||
try {
|
||||
if (list == null || list.isEmpty()) {
|
||||
mDao.clearControls();
|
||||
return;
|
||||
}
|
||||
List<AppTimeControlEntity> entities = new ArrayList<>();
|
||||
final List<AppTimeControlEntity> entities = new ArrayList<>();
|
||||
if (list != null) {
|
||||
for (AppTimeControlInfo info : list) {
|
||||
if (TextUtils.isEmpty(info.getApp_package())) continue; // 防御空包名
|
||||
if (info == null || TextUtils.isEmpty(info.getApp_package())) continue; // 防御空包名
|
||||
entities.add(toEntity(info));
|
||||
}
|
||||
mDao.clearControls();
|
||||
if (!entities.isEmpty()) {
|
||||
mDao.insertControls(entities);
|
||||
}
|
||||
Log.e(TAG, "Saved App controls to Room, size=" + entities.size());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to save App controls to Room: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Room 加载所有受限应用的剩余时长(重启恢复用)。
|
||||
*/
|
||||
public List<AppRemainingEntity> loadRemainingFromDb() {
|
||||
try {
|
||||
return mDao.getAllRemaining();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to load remaining from Room: " + e.getMessage());
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Observable.fromCallable(() -> {
|
||||
mDb.runInTransaction(() -> {
|
||||
mDao.clearControls();
|
||||
if (!entities.isEmpty()) {
|
||||
mDao.insertControls(entities);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}).subscribeOn(DB_WRITE_SCHEDULER).subscribe(
|
||||
ignored -> Log.e(TAG, "Saved App controls to Room, size=" + entities.size()),
|
||||
e -> Log.e(TAG, "Failed to save App controls to Room: " + e.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单个应用剩余时长写入 Room(节流调用,见 TimeManager)。
|
||||
* 使用 REPLACE 插入,保证行不存在时也能落库。
|
||||
*/
|
||||
public void saveRemainingToDb(String pkg, long remaining) {
|
||||
try {
|
||||
mDao.updateRemaining(pkg, remaining, System.currentTimeMillis());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to save remaining to Room: " + e.getMessage());
|
||||
}
|
||||
final AppRemainingEntity entity = new AppRemainingEntity();
|
||||
entity.app_package = pkg;
|
||||
entity.remaining_seconds = remaining;
|
||||
entity.updated_at = System.currentTimeMillis();
|
||||
Observable.fromCallable(() -> {
|
||||
mDao.insertRemaining(entity);
|
||||
return true;
|
||||
}).subscribeOn(DB_WRITE_SCHEDULER).subscribe(
|
||||
ignored -> { },
|
||||
e -> Log.e(TAG, "Failed to save remaining to Room: " + e.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量写入剩余时长(跨天重置或整体恢复时用)。
|
||||
* 批量写入剩余时长(跨天重置或整体恢复时用),事务内完成 clear + insert。
|
||||
*/
|
||||
public void saveRemainingBatchToDb(List<AppRemainingEntity> entities) {
|
||||
try {
|
||||
mDao.clearRemaining();
|
||||
mDao.insertRemaining(entities);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to save remaining batch to Room: " + e.getMessage());
|
||||
}
|
||||
final List<AppRemainingEntity> rows = entities == null
|
||||
? new ArrayList<>() : new ArrayList<>(entities);
|
||||
Observable.fromCallable(() -> {
|
||||
mDb.runInTransaction(() -> {
|
||||
mDao.clearRemaining();
|
||||
if (!rows.isEmpty()) {
|
||||
mDao.insertRemaining(rows);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}).subscribeOn(DB_WRITE_SCHEDULER).subscribe(
|
||||
ignored -> { },
|
||||
e -> Log.e(TAG, "Failed to save remaining batch to Room: " + e.getMessage()));
|
||||
}
|
||||
|
||||
// --- 剩余时长持久化(与 RunningAppManager 共享同一 MMKV key) ---
|
||||
@@ -488,6 +513,21 @@ public class TimeConfigRepository {
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room 中持久化的管控数据快照,供启动恢复时一次性取回。
|
||||
*/
|
||||
public static final class PersistedConfig {
|
||||
/** Room 中的 App 管控配置,空列表表示 Room 无数据 */
|
||||
public final List<AppTimeControlInfo> appControls;
|
||||
/** Room 中已扣减后的剩余时长 */
|
||||
public final List<AppRemainingEntity> remaining;
|
||||
|
||||
PersistedConfig(List<AppTimeControlInfo> appControls, List<AppRemainingEntity> remaining) {
|
||||
this.appControls = appControls;
|
||||
this.remaining = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务层请求失败(HTTP 成功但 BaseResponse.code != 200,如 400 请求过于频繁)时抛出,
|
||||
* 用于触发 retryWhen 的延时重试。
|
||||
|
||||
@@ -212,7 +212,7 @@ public class ApkUtils {
|
||||
for (ApplicationInfo app : appInfos) {
|
||||
// Log.e(TAG, "queryFilterAppInfo: " + String.valueOf(app.flags));
|
||||
// Log.e(TAG, "queryFilterAppInfo: " + String.valueOf((app.flags & mask)));
|
||||
if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
|
||||
if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
|
||||
//通过flag排除系统应用,会将电话、短信也排除掉
|
||||
} else {
|
||||
applicationInfos.add(app.packageName);
|
||||
@@ -541,10 +541,12 @@ public class ApkUtils {
|
||||
Log.e(TAG, "isSystemApp: NameNotFoundException: " + e.getMessage());
|
||||
}
|
||||
// 是系统中已安装的应用
|
||||
if (pi != null) {
|
||||
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
|
||||
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
|
||||
isSystemApp = isSysApp || isSysUpd;
|
||||
if (pi != null && pi.applicationInfo != null) {
|
||||
// 标志位是按位与,结果只可能等于 0 或该标志位本身,不能写成 == 1:
|
||||
// FLAG_UPDATED_SYSTEM_APP 是 0x80,写成 == 1 会恒为 false,
|
||||
// 导致覆盖升级过的系统应用被误判成第三方应用。
|
||||
int flags = pi.applicationInfo.flags;
|
||||
isSystemApp = (flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
|
||||
}
|
||||
return isSystemApp;
|
||||
}
|
||||
|
||||
@@ -562,29 +562,6 @@ public class RunningAppManager {
|
||||
KVStore.encode(AllApplUsageTimeMap, singleString);
|
||||
}
|
||||
|
||||
private long getAppTodayRunTime(String pkg) {
|
||||
AppInformation appInformation = getInfoFromPackageName(mContext, pkg);
|
||||
if (appInformation == null) {
|
||||
return 0;
|
||||
} else {
|
||||
return appInformation.getUsedTimebyDay() / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
public static AppInformation getInfoFromPackageName(Context context, String packageName) {
|
||||
List<AppInformation> list;
|
||||
AppInformation app = null;
|
||||
StatisticsInfo statisticsInfo = new StatisticsInfo(context);
|
||||
list = statisticsInfo.getShowList();
|
||||
for (AppInformation appInformation : list) {
|
||||
String name = appInformation.getPackageName();
|
||||
if (appInformation.getPackageName().equals(packageName)) {
|
||||
return appInformation;
|
||||
}
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取剩余时间
|
||||
*
|
||||
|
||||
@@ -39,7 +39,7 @@ public class TimeControlManager {
|
||||
throw new RuntimeException("Context is NULL");
|
||||
}
|
||||
this.mContext = context;
|
||||
this.mCacheHelper = new CacheHelper(context);
|
||||
this.mCacheHelper = CacheHelper.getInstance(context);
|
||||
String appTimeControlJson = mCacheHelper.getAsString(UrlAddress.GET_APP_TIME_CONTROL);
|
||||
if (!TextUtils.isEmpty(appTimeControlJson)) {
|
||||
Gson gson = new Gson();
|
||||
|
||||
@@ -106,6 +106,14 @@ public class TimeManager {
|
||||
* 跨天/异常时刷新配置的订阅句柄(重试策略已内聚在 TimeConfigRepository)
|
||||
*/
|
||||
private Disposable mConfigRetryDisposable;
|
||||
/**
|
||||
* 启动时异步恢复 Room 配置的订阅句柄
|
||||
*/
|
||||
private Disposable mPersistedConfigDisposable;
|
||||
/**
|
||||
* 管控配置版本号:服务端下发新配置时自增,用于丢弃过期的本地恢复结果
|
||||
*/
|
||||
private int mConfigVersion;
|
||||
private static final long APP_LIST_FALLBACK_INTERVAL_MS = TimeUnit.MINUTES.toMillis(5);
|
||||
private final AtomicLong mNextAppListFallbackAt = new AtomicLong();
|
||||
|
||||
@@ -114,6 +122,9 @@ public class TimeManager {
|
||||
*/
|
||||
private long mLastRemainingDbWrite = 0;
|
||||
private static final long REMAINING_WRITE_INTERVAL = 5000; // 节流间隔 5 秒
|
||||
private String mLastToastMessage;
|
||||
private long mLastToastTime = 0;
|
||||
private static final long TOAST_INTERVAL = 5000; // 同一拦截提示 5 秒内只弹一次
|
||||
|
||||
/**
|
||||
* 免管控白名单,包含系统核心组件及特定工具应用
|
||||
@@ -289,26 +300,38 @@ public class TimeManager {
|
||||
|
||||
/**
|
||||
* 从本地缓存加载管控配置,保证离线可用性。
|
||||
* App 配置优先从 Room 恢复;剩余时长也从 Room 恢复(防止重启后绕过管控)。
|
||||
* 主线程只读 MMKV,保证 SN 配置与兜底 App 列表立即可用;
|
||||
* Room 中的 App 配置与已扣减剩余时长在 IO 线程读取后覆盖。
|
||||
*/
|
||||
private void loadLocalConfig() {
|
||||
mConfigRepository.loadLocalConfig();
|
||||
mConfigRepository.loadCacheConfig();
|
||||
mSnTimeControlInfo = mConfigRepository.getSnTimeControlInfo();
|
||||
mGlobalRemainingTime = mConfigRepository.loadGlobalRemainingTime();
|
||||
|
||||
// 若本地有 App 配置缓存,则同步构建管控 Map,保证离线时应用也能被管控
|
||||
List<AppTimeControlInfo> appList = mConfigRepository.getAppTimeControlList();
|
||||
rebuildAppMaps(appList);
|
||||
// 先用 MMKV 兜底数据构建管控 Map,避免 Room 读取期间出现空管控
|
||||
rebuildAppMaps(mConfigRepository.getAppTimeControlList());
|
||||
|
||||
// 从 Room 恢复已扣减后的剩余时长(若存在),否则沿用今日配额
|
||||
List<AppRemainingEntity> remainingList = mConfigRepository.loadRemainingFromDb();
|
||||
if (remainingList != null && !remainingList.isEmpty()) {
|
||||
for (AppRemainingEntity entity : remainingList) {
|
||||
if (TextUtils.isEmpty(entity.app_package)) continue;
|
||||
mRemainingTimeMap.put(entity.app_package, entity.remaining_seconds);
|
||||
}
|
||||
Log.e(TAG, "Restored remaining time from Room, size=" + remainingList.size());
|
||||
}
|
||||
// Room 数据异步恢复:期间若服务端已下发新配置,则丢弃本次结果
|
||||
final int version = mConfigVersion;
|
||||
mPersistedConfigDisposable = mConfigRepository.loadPersistedConfig()
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(config -> {
|
||||
if (version != mConfigVersion) {
|
||||
Log.e(TAG, "loadLocalConfig: config updated, skip persisted config");
|
||||
return;
|
||||
}
|
||||
if (config.appControls != null && !config.appControls.isEmpty()) {
|
||||
rebuildAppMaps(config.appControls);
|
||||
}
|
||||
// 从 Room 恢复已扣减后的剩余时长(若存在),否则沿用今日配额
|
||||
if (config.remaining != null && !config.remaining.isEmpty()) {
|
||||
for (AppRemainingEntity entity : config.remaining) {
|
||||
if (TextUtils.isEmpty(entity.app_package)) continue;
|
||||
mRemainingTimeMap.put(entity.app_package, entity.remaining_seconds);
|
||||
}
|
||||
Log.e(TAG, "Restored remaining time from Room, size=" + config.remaining.size());
|
||||
}
|
||||
}, error -> Log.e(TAG, "loadPersistedConfig failed", error));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -423,7 +446,7 @@ public class TimeManager {
|
||||
|
||||
// 应用是否被手动禁用 (is_control == 0)
|
||||
if (appInfo.getIs_control() == 0) {
|
||||
Toaster.show("应用已被禁用");
|
||||
showControlToast("应用已被禁用");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -442,14 +465,14 @@ public class TimeManager {
|
||||
switch (snType) {
|
||||
case 1: // 整机限时:如果整机时间耗尽,则拦截(无论应用是否开启独立时长)
|
||||
if (mGlobalRemainingTime <= 0) {
|
||||
Toaster.show("今日整机使用时长已超限");
|
||||
showControlToast("今日整机使用时长已超限");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case 2: // 整机限时间段:当前时间需在整机允许的时间段内
|
||||
List<PartTime> snParts = mSnTimeControlInfo.getTime_part();
|
||||
if (!isDefaultTimePeriod(snParts) && !inOpenTimePeriod(snParts)) {
|
||||
Toaster.show("当前时间不在设备的可使用时间段内");
|
||||
showControlToast("当前时间不在设备的可使用时间段内");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
@@ -465,13 +488,13 @@ public class TimeManager {
|
||||
case 1: // 应用时长限制:检查该应用剩余时长
|
||||
Long remain = mRemainingTimeMap.get(pkg);
|
||||
if (remain == null || remain <= 0) {
|
||||
Toaster.show("今日该应用使用时长已超限");
|
||||
showControlToast("今日该应用使用时长已超限");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case 2: // 应用时间段限制:检查当前是否在应用允许的时间段
|
||||
if (!inOpenTimePeriod(appInfo.getTime_part())) {
|
||||
Toaster.show("当前时间不在应用的可使用时间段内");
|
||||
showControlToast("当前时间不在应用的可使用时间段内");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
@@ -479,6 +502,19 @@ public class TimeManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截提示去重:每秒轮询会反复触发拦截,同一提示 5 秒内只弹一次,避免 Toast 堆积
|
||||
*/
|
||||
private void showControlToast(String message) {
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (TextUtils.equals(message, mLastToastMessage) && now - mLastToastTime < TOAST_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
mLastToastMessage = message;
|
||||
mLastToastTime = now;
|
||||
Toaster.show(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 时长扣减逻辑:根据当前整机模式和应用模式,扣减相应的计数器。
|
||||
* 优化点:只要整机开启了限时模式,所有管控应用的使用都会扣减整机时长。
|
||||
@@ -658,6 +694,8 @@ public class TimeManager {
|
||||
@Override
|
||||
public void onAppConfigUpdated(List<AppTimeControlInfo> list) {
|
||||
Log.e(TAG, "onAppConfigUpdated: " );
|
||||
// 配置已更新,启动时的 Room 恢复结果即使稍后返回也应丢弃
|
||||
mConfigVersion++;
|
||||
rebuildAppMaps(list);
|
||||
// 新配置下发后,用当日配额刷新 Room 剩余时长表
|
||||
saveAllRemainingToDb();
|
||||
@@ -788,6 +826,10 @@ public class TimeManager {
|
||||
public synchronized void onDestroy() {
|
||||
ReceiverCompat.unregisterReceiver(mContext, mTimeChangedReceiver);
|
||||
mTimeChangedReceiver = null;
|
||||
if (mPersistedConfigDisposable != null && !mPersistedConfigDisposable.isDisposed()) {
|
||||
mPersistedConfigDisposable.dispose();
|
||||
}
|
||||
mPersistedConfigDisposable = null;
|
||||
if (isConfigFetchRunning()) {
|
||||
mConfigRetryDisposable.dispose();
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ public final class RuntimeInitializers {
|
||||
|
||||
@Override
|
||||
public void init(Application application) {
|
||||
CacheHelper syncCache = new CacheHelper(application);
|
||||
CacheHelper syncCache = CacheHelper.getInstance(application);
|
||||
DeviceRepository.init(application, syncCache);
|
||||
DeviceProfileSync.init(application);
|
||||
PushTagSync.init();
|
||||
|
||||
@@ -72,7 +72,7 @@ public class PushManager {
|
||||
throw new RuntimeException("Context is NULL");
|
||||
}
|
||||
this.mContext = context.getApplicationContext();
|
||||
this.mCacheHelper = new CacheHelper(context);
|
||||
this.mCacheHelper = CacheHelper.getInstance(context);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.fuying.sn.core.data.remote.BackgroundRequests;
|
||||
import com.fuying.sn.core.data.repository.DeviceRepository;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
@@ -111,38 +112,53 @@ public class LogcatService extends BaseService {
|
||||
ReceiverCompat.registerReceiver(this, receiver, filter, ReceiverCompat.RECEIVER_EXPORTED);
|
||||
}
|
||||
|
||||
Thread thread = null;
|
||||
private volatile Thread thread = null;
|
||||
// 当前采集进程,STOP 时销毁它,打断阻塞中的 readLine
|
||||
private volatile Process mLogProcess = null;
|
||||
|
||||
private void creatLogThread() {
|
||||
if (thread == null) {
|
||||
// 常驻采集线程:命名便于排查,设为守护线程避免进程退出时被它拖住
|
||||
thread = new Thread(LogcatRunnale, "Logcat-Collector");
|
||||
thread.setDaemon(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void startLogThread() {
|
||||
if (thread == null) {
|
||||
creatLogThread();
|
||||
shouldGetLog = true;
|
||||
thread.start();
|
||||
} else {
|
||||
//已经有线程正在运行了
|
||||
private synchronized void startLogThread() {
|
||||
if (thread != null) {
|
||||
Log.e(TAG, "startLogThread: already running");
|
||||
return;
|
||||
}
|
||||
shouldGetLog = true;
|
||||
// 常驻采集线程:命名便于排查,设为守护线程避免进程退出时被它拖住
|
||||
thread = new Thread(LogcatRunnale, "Logcat-Collector");
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
private void stopLogThread() {
|
||||
if (thread != null) {
|
||||
Process process;
|
||||
synchronized (this) {
|
||||
shouldGetLog = false;
|
||||
thread = null;
|
||||
//清除adb 缓存
|
||||
try {
|
||||
Runtime.getRuntime().exec(clearLogcat);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "stopLogThread: " + e.getMessage(), e);
|
||||
}
|
||||
process = mLogProcess;
|
||||
}
|
||||
if (process == null) {
|
||||
// 采集线程已结束并在 finally 中完成上传,避免重复上传
|
||||
return;
|
||||
}
|
||||
// 销毁进程打断 readLine,收尾与上传由采集线程的 finally 统一处理
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
private void clearLogcatBuffer() {
|
||||
try {
|
||||
Runtime.getRuntime().exec(clearLogcat);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "clearLogcatBuffer: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void closeQuietly(Closeable closeable) {
|
||||
if (closeable == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "closeQuietly: " + e.getMessage(), e);
|
||||
}
|
||||
uploadFile();
|
||||
}
|
||||
|
||||
|
||||
@@ -205,62 +221,77 @@ public class LogcatService extends BaseService {
|
||||
|
||||
private Runnable LogcatRunnale = this::getLog;
|
||||
|
||||
public static boolean shouldGetLog = true;
|
||||
public static volatile boolean shouldGetLog = true;
|
||||
|
||||
private void getLog() {
|
||||
Process process = null;
|
||||
BufferedReader bufferedReader = null;
|
||||
FileOutputStream fileOutputStream = null;
|
||||
tempFilePath = null;
|
||||
try {
|
||||
process = Runtime.getRuntime().exec(running);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "getLog: " + e.getMessage(), e);
|
||||
}
|
||||
InputStreamReader inputStreamReader;
|
||||
BufferedReader bufferedReader;
|
||||
FileOutputStream fileOutputStream;
|
||||
File file = new File(logFilePath);
|
||||
Log.e(TAG, "getLog: " + logFilePath);
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();
|
||||
}
|
||||
mLogProcess = process;
|
||||
File file = new File(logFilePath);
|
||||
Log.e(TAG, "getLog: " + logFilePath);
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();
|
||||
}
|
||||
|
||||
if (clear_file) {
|
||||
logFileName = DeviceIdUtils.getSerial() + ".log";
|
||||
} else {
|
||||
logFileName = DeviceIdUtils.getSerial() + "-" + getTime() + ".log";
|
||||
}
|
||||
if (clear_file) {
|
||||
logFileName = DeviceIdUtils.getSerial() + ".log";
|
||||
} else {
|
||||
logFileName = DeviceIdUtils.getSerial() + "-" + getTime() + ".log";
|
||||
}
|
||||
|
||||
try {
|
||||
inputStreamReader = new InputStreamReader(process.getInputStream());
|
||||
bufferedReader = new BufferedReader(inputStreamReader);
|
||||
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
tempFilePath = logFilePath + logFileName;
|
||||
fileOutputStream = new FileOutputStream(tempFilePath);
|
||||
Log.e(TAG, "getLog: " + tempFilePath);
|
||||
long fileSize = file.length();
|
||||
String logEntry;
|
||||
long fileSize = new File(tempFilePath).length();
|
||||
while (shouldGetLog) {
|
||||
logEntry = bufferedReader.readLine() + "\n";
|
||||
String line = bufferedReader.readLine();
|
||||
if (line == null) {
|
||||
// logcat 进程被销毁或异常退出,结束本轮采集
|
||||
break;
|
||||
}
|
||||
String logEntry = line + "\n";
|
||||
fileOutputStream.write(logEntry.getBytes());
|
||||
fileOutputStream.flush();
|
||||
fileSize += logEntry.length();
|
||||
// Log.e(TAG, "getLog: " + fileSize);
|
||||
if (fileSize >= condition_file_max_size ||
|
||||
(start_Time + condition_duration) * 1000 < System.currentTimeMillis()) {
|
||||
shouldGetLog = false;
|
||||
stopLogThread();
|
||||
}
|
||||
}
|
||||
inputStreamReader.close();
|
||||
bufferedReader.close();
|
||||
fileOutputStream.close();
|
||||
Log.e(TAG, "getLog: " + "closed");
|
||||
Log.e(TAG, "getLog: closed");
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "getLog: " + e.getMessage(), e);
|
||||
} catch (NullPointerException e) {
|
||||
Log.e(TAG, "getLog: " + e.getMessage(), e);
|
||||
} finally {
|
||||
closeQuietly(bufferedReader);
|
||||
closeQuietly(fileOutputStream);
|
||||
if (process != null) {
|
||||
process.destroy();
|
||||
}
|
||||
synchronized (this) {
|
||||
if (thread == Thread.currentThread()) {
|
||||
thread = null;
|
||||
shouldGetLog = false;
|
||||
}
|
||||
mLogProcess = null;
|
||||
}
|
||||
// 文件流关闭后再统一清 adb 缓存并上传,避免上传到不完整文件
|
||||
clearLogcatBuffer();
|
||||
uploadFile();
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadFile() {
|
||||
if (TextUtils.isEmpty(tempFilePath)) {
|
||||
Log.e(TAG, "uploadFile: tempFilePath is empty");
|
||||
return;
|
||||
}
|
||||
File file = new File(tempFilePath);
|
||||
if (!file.exists() || file.isDirectory()) {
|
||||
Log.e(TAG, "uploadFile: File does not exists");
|
||||
@@ -330,6 +361,7 @@ public class LogcatService extends BaseService {
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
stopLogThread();
|
||||
if (receiver != null) {
|
||||
ReceiverCompat.unregisterReceiver(this, receiver);
|
||||
}
|
||||
|
||||
@@ -15,11 +15,14 @@ import com.fuying.sn.core.data.repository.DeviceRepository;
|
||||
import com.fuying.sn.platform.app.ApkUtils;
|
||||
import com.fuying.sn.runtime.sync.RequestCallbacks.CompleteCallback;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import io.reactivex.rxjava3.annotations.NonNull;
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import io.reactivex.rxjava3.core.Observer;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
|
||||
/**
|
||||
* 上报应用使用记录,保存上传失败的记录,并在网络恢复时补传。
|
||||
@@ -96,70 +99,61 @@ public final class AppUsageReporter {
|
||||
|
||||
/**
|
||||
* 将应用使用记录保存到 Room,用于上传失败后网络恢复时的重新上传。
|
||||
* 入库在 IO 线程执行,避免阻塞网络回调所在的主线程。
|
||||
*/
|
||||
private void saveAppUsageRecordToRoom(String packageName, String label, long openTime, long closeTime) {
|
||||
try {
|
||||
AppUsageRecordEntity entity = new AppUsageRecordEntity();
|
||||
entity.setApp_package(packageName);
|
||||
entity.setApp_name(label);
|
||||
entity.setOpen_time(openTime);
|
||||
entity.setClose_time(closeTime);
|
||||
AppUsageRecordEntity entity = new AppUsageRecordEntity();
|
||||
entity.setApp_package(packageName);
|
||||
entity.setApp_name(label);
|
||||
entity.setOpen_time(openTime);
|
||||
entity.setClose_time(closeTime);
|
||||
Observable.fromCallable(() -> {
|
||||
AppUsageRecordDatabase.getInstance(mContext).appUsageRecordDao().insert(entity);
|
||||
Log.e(TAG, "saveAppUsageRecordToRoom: 上传失败,已缓存到 Room packageName = " + packageName);
|
||||
} catch (Exception ex) {
|
||||
Log.e(TAG, "saveAppUsageRecordToRoom: " + ex.getMessage());
|
||||
}
|
||||
return true;
|
||||
}).subscribeOn(Schedulers.io()).subscribe(
|
||||
ignored -> Log.e(TAG, "saveAppUsageRecordToRoom: 上传失败,已缓存到 Room packageName = " + packageName),
|
||||
ex -> Log.e(TAG, "saveAppUsageRecordToRoom: " + ex.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络恢复后,读取 Room 中缓存的应用使用记录并重新上传。
|
||||
* 上传成功的记录会从数据库中删除。
|
||||
* 读取、上传、删除全部在后台线程串行执行,上传成功的记录会从数据库中删除。
|
||||
*/
|
||||
public void reUploadAppUsageRecords() {
|
||||
try {
|
||||
List<AppUsageRecordEntity> records =
|
||||
AppUsageRecordDatabase.getInstance(mContext).appUsageRecordDao().getAllRecords();
|
||||
if (records == null || records.isEmpty()) {
|
||||
Log.e(TAG, "reUploadAppUsageRecords: 无待上传记录");
|
||||
return;
|
||||
}
|
||||
Log.e(TAG, "reUploadAppUsageRecords: 待上传记录数 = " + records.size());
|
||||
for (AppUsageRecordEntity entity : records) {
|
||||
long id = entity.getId();
|
||||
String packageName = entity.getApp_package();
|
||||
String label = entity.getApp_name();
|
||||
long openTime = entity.getOpen_time();
|
||||
long closeTime = entity.getClose_time();
|
||||
repository.getAppUsageRecordObservable(packageName, label, openTime, closeTime)
|
||||
.to(BackgroundRequests.submit(new Observer<BaseResponse>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
}
|
||||
Observable.fromCallable(() ->
|
||||
AppUsageRecordDatabase.getInstance(mContext).appUsageRecordDao().getAllRecords())
|
||||
.subscribeOn(Schedulers.io())
|
||||
.map(records -> records == null ? Collections.<AppUsageRecordEntity>emptyList() : records)
|
||||
.doOnNext(records -> {
|
||||
if (records.isEmpty()) {
|
||||
Log.e(TAG, "reUploadAppUsageRecords: 无待上传记录");
|
||||
} else {
|
||||
Log.e(TAG, "reUploadAppUsageRecords: 待上传记录数 = " + records.size());
|
||||
}
|
||||
})
|
||||
.flatMapIterable(records -> records)
|
||||
.concatMap(this::reUploadOne)
|
||||
.subscribe(ignored -> { },
|
||||
ex -> Log.e(TAG, "reUploadAppUsageRecords: " + ex.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseResponse baseResponse) {
|
||||
Log.e(TAG, "reUploadAppUsageRecord: onNext: " + baseResponse);
|
||||
// 上传成功,从数据库删除
|
||||
if (baseResponse != null && baseResponse.code == 200) {
|
||||
AppUsageRecordDatabase.getInstance(mContext).appUsageRecordDao().deleteById(id);
|
||||
Log.e(TAG, "reUploadAppUsageRecord: 上传成功并删除缓存 id = " + id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
Log.e(TAG, "reUploadAppUsageRecord: onError: " + e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
Log.e(TAG, "reUploadAppUsageRecord: onComplete: ");
|
||||
}
|
||||
}));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.e(TAG, "reUploadAppUsageRecords: " + ex.getMessage());
|
||||
}
|
||||
/**
|
||||
* 串行补传单条记录,成功后删除对应缓存。
|
||||
*/
|
||||
private Observable<Boolean> reUploadOne(AppUsageRecordEntity entity) {
|
||||
final long id = entity.getId();
|
||||
return repository.getAppUsageRecordObservable(entity.getApp_package(), entity.getApp_name(),
|
||||
entity.getOpen_time(), entity.getClose_time())
|
||||
.map(response -> response != null && response.code == 200)
|
||||
.onErrorReturnItem(false)
|
||||
.observeOn(Schedulers.io())
|
||||
.map(success -> {
|
||||
if (success) {
|
||||
AppUsageRecordDatabase.getInstance(mContext).appUsageRecordDao().deleteById(id);
|
||||
Log.e(TAG, "reUploadAppUsageRecord: 上传成功并删除缓存 id = " + id);
|
||||
}
|
||||
return success;
|
||||
});
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:id="@+id/root"
|
||||
tools:context=".activity.GuideActivity">
|
||||
|
||||
<com.github.chrisbanes.photoview.PhotoView
|
||||
android:id="@+id/photoView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
Reference in new issue
Block a user