refactor(core): 重构核心模块初始化与异步调度机制

- 初始化注册表增加延迟兜底任务与失败模块跳过机制
- 优化注册表锁粒度,执行阶段不再持锁避免阻塞
- 增加各初始化器分段耗时日志便于定位启动瓶颈
- 推送模块用 RxJava SerialDisposable 替代 Handler 重试调度
- 用 PublishSubject 防抖替代 Handler postDelayed 防抖
- 修复 CrashGuard 默认处理器未退出进程导致假活问题
- 清理广播接收器静态 Context 引用及冗余逻辑
- 移除 AndroidManifest 中不必要的权限声明
- 统一日志级别与 TAG 命名规范
- style(sync): 整理 AppPolicySync 的 import 语句顺序,移除未使用 import、按包名分组、移除多余空行
This commit is contained in:
tongtong committed 2026-11-18 17:26:47 +08:00
1 parent f53ce61752
commit 613aa18a0f
12 files changed
+233 -166

No files matched your search

+1 -2
View File
@@ -171,8 +171,7 @@
<receiver
android:name=".runtime.receiver.ApkInstallReceiver"
android:enabled="true"
android:exported="true"
android:permission="com.example.broadcast.permission">
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
@@ -18,9 +18,6 @@ import com.fuying.sn.runtime.init.RuntimeInitializers;
public class BaseApplication extends Application {
private static final String TAG = "BaseApplication";
/**
* ViewModel中因为经常旋转导致弱引用为空
*/
@SuppressLint("StaticFieldLeak")
private static BaseApplication sInstance;
@@ -37,14 +34,6 @@ public class BaseApplication extends Application {
//非主进程不初始化
if (SystemUtils.isMainProcessName(this, android.os.Process.myPid())) {
if (BuildConfig.DEBUG) {
//静音
// AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// int ringMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_RING);
// audioManager.setStreamVolume(AudioManager.STREAM_RING, ringMax, 0);
// int musicMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_MUSIC);
// int voiceMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_VOICE_CALL);
// audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, voiceMax, 0);
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicMax, 0); //音乐音量
Log.e(TAG, "debugTest: " + getExternalCacheDir());
Log.e(TAG, "debugTest: " + getExternalFilesDir("cache"));
Log.e(TAG, "debugTest: " + getCacheDir());
@@ -36,6 +36,9 @@ public interface AppInitializer {
* <p>返回 false 时 init 整体推迟到首帧后的主线程空闲阶段,
* 适用于不影响常驻服务启动、广播接收注册的模块。
*
* <p>注意:当前登记的初始化器全部返回 true,false 分支是为已验证无前置依赖的模块预留,
* 迁移某个模块前需确认它不会被常驻服务在启动瞬间调用。
*
* @return 必须同步初始化返回 true
*/
boolean required();
@@ -4,6 +4,7 @@ import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import java.util.ArrayList;
@@ -12,6 +13,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 初始化器注册表:收集各模块的初始化器,按依赖推导执行顺序,并分两个阶段执行。
@@ -23,12 +25,27 @@ public final class AppInitializerRegistry {
private static final String TAG = "AppInitializerRegistry";
/**
* 延迟阶段的兜底延时:主线程长时间不空闲时,到点也要把延迟动作跑掉
*/
private static final long DEFERRED_FALLBACK_DELAY_MS = 3_000L;
/**
* 用 LinkedHashMap 保留登记顺序,依赖相同时排序结果才稳定
*/
private static final Map<Class<?>, AppInitializer> sInitializers = new LinkedHashMap<>();
/**
* 初始化失败的模块,延迟阶段直接跳过,避免拿半初始化的对象再抛一次异常
*/
private static final Set<Class<?>> sFailed = new HashSet<>();
/**
* 延迟动作只允许执行一次:空闲回调与延时兜底谁先到谁执行
*/
private static final AtomicBoolean sDeferredRun = new AtomicBoolean(false);
private static List<AppInitializer> sOrdered;
private static boolean sDeferredStarted;
private static boolean sSealed;
private static boolean sDeferredScheduled;
private AppInitializerRegistry() {
}
@@ -42,6 +59,11 @@ public final class AppInitializerRegistry {
if (initializers == null) {
return;
}
if (sSealed) {
// 执行阶段开始后登记会造成顺序与快照不一致,直接拒绝
Log.e(TAG, "install: 初始化已开始执行,拒绝后续登记");
return;
}
for (AppInitializer initializer : initializers) {
if (initializer == null) {
continue;
@@ -62,8 +84,18 @@ public final class AppInitializerRegistry {
*
* @param application 应用上下文
*/
public static synchronized void runRequired(Application application) {
for (AppInitializer initializer : ordered()) {
public static void runRequired(Application application) {
final List<AppInitializer> ordered;
synchronized (AppInitializerRegistry.class) {
if (sSealed) {
Log.e(TAG, "runRequired: 已执行过,忽略重复调用");
return;
}
sSealed = true;
ordered = ordered();
}
// 排序快照已取出,执行期间不再持锁,避免阻塞其它线程访问注册表
for (AppInitializer initializer : ordered) {
if (initializer.required()) {
execute(initializer, application, false);
}
@@ -71,32 +103,51 @@ public final class AppInitializerRegistry {
}
/**
* 挂起延迟初始化,在主线程首轮消息跑完后的空闲阶段执行。
* 挂起延迟初始化,在主线程首轮消息跑完后的空闲阶段执行,长时间不空闲时由延时任务兜底。
*
* @param application 应用上下文
*/
public static void runDeferred(final Application application) {
final List<AppInitializer> ordered;
synchronized (AppInitializerRegistry.class) {
if (sDeferredStarted) {
if (sDeferredScheduled) {
Log.e(TAG, "runDeferred: 已挂起过,忽略重复调用");
return;
}
sDeferredStarted = true;
sDeferredScheduled = true;
ordered = ordered();
}
final Runnable deferredTask = new Runnable() {
@Override
public void run() {
if (!sDeferredRun.compareAndSet(false, true)) {
return;
}
for (AppInitializer initializer : ordered) {
execute(initializer, application, true);
}
}
};
// 先让 onCreate 返回后的首轮消息与首帧先跑完,再挂空闲任务,避免和绘制抢主线程
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
final MessageQueue.IdleHandler idleHandler = new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
for (AppInitializer initializer : ordered) {
execute(initializer, application, true);
}
deferredTask.run();
return false;
}
});
};
Looper.myQueue().addIdleHandler(idleHandler);
// 常驻服务较多时主线程可能长期不空闲,用延时任务兜底,二者由一次性开关互斥
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
Looper.myQueue().removeIdleHandler(idleHandler);
deferredTask.run();
}
}, DEFERRED_FALLBACK_DELAY_MS);
}
});
}
@@ -104,12 +155,20 @@ public final class AppInitializerRegistry {
/**
* 执行单个初始化器,失败只记录不中断,避免一个模块拖垮整个启动流程。
*
* <p>只拦截 Exception:Error 说明运行环境已不可恢复,交给默认处理器上报并重启。
*
* @param initializer 初始化器
* @param application 应用上下文
* @param deferredPhase 是否处于延迟阶段
*/
private static void execute(AppInitializer initializer, Application application, boolean deferredPhase) {
String name = initializer.getClass().getSimpleName();
Class<?> type = initializer.getClass();
String stage = deferredPhase ? "deferred" : "required";
if (deferredPhase && sFailed.contains(type)) {
Log.e(TAG, "execute: " + type.getSimpleName() + " 初始化已失败,跳过延迟动作");
return;
}
long start = SystemClock.elapsedRealtime();
try {
if (!deferredPhase) {
initializer.init(application);
@@ -120,18 +179,25 @@ public final class AppInitializerRegistry {
initializer.init(application);
}
initializer.deferred(application);
} catch (Throwable e) {
} catch (Exception e) {
// 单个模块初始化失败不阻断其它模块,但必须留下可定位的日志
Log.e(TAG, "execute: " + name + " 初始化失败,阶段=" + (deferredPhase ? "deferred" : "required")
sFailed.add(type);
Log.e(TAG, "execute: " + type.getSimpleName() + " 初始化失败,阶段=" + stage
+ " " + Log.getStackTraceString(e));
} finally {
// 分段耗时是定位启动慢的直接依据,成本和一行普通日志相当
Log.i(TAG, "execute: " + type.getSimpleName() + " 阶段=" + stage
+ " 耗时=" + (SystemClock.elapsedRealtime() - start) + "ms");
}
}
private static synchronized List<AppInitializer> ordered() {
if (sOrdered == null) {
sOrdered = sort(new ArrayList<>(sInitializers.values()));
private static List<AppInitializer> ordered() {
synchronized (AppInitializerRegistry.class) {
if (sOrdered == null) {
sOrdered = sort(new ArrayList<>(sInitializers.values()));
}
return sOrdered;
}
return sOrdered;
}
/**
@@ -50,7 +50,8 @@ public final class CoreInitializers {
@Override
public void init(Application application) {
String rootDir = MMKV.initialize(application);
Log.e(TAG, "init: mmkv root = " + rootDir);
// 启动路径信息用 info 级别,避免污染 Bugly 的错误日志检索
Log.i(TAG, "init: mmkv root = " + rootDir);
}
}
@@ -88,11 +88,13 @@ public final class CrashGuard implements AppInitializer {
Log.e(TAG, "catchException: 主线程连续异常次数=" + crashCount);
if (originHandler != null) {
originHandler.uncaughtException(Thread.currentThread(), e);
return;
// 默认处理器可能只上报不退出(Bugly 可配置),此时主线程循环已经结束,
// 若不补刀会让进程假活、所有消息停止分发,这里必须确保进程真正结束
Log.e(TAG, "catchException: 默认处理器已执行,主动结束进程");
}
// 没有兜底处理器时主动结束进程,避免带着已损坏的状态继续分发消息
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
return;
}
reportCatchedException(e);
}
@@ -2,8 +2,6 @@ package com.fuying.sn.runtime.push;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
@@ -18,6 +16,13 @@ import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.disposables.SerialDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
/**
* 阿里云移动推送统一管理类。
@@ -77,7 +82,22 @@ public class AliyunPushManager {
private final Context mContext;
private final Application mApplication;
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* 注册重试任务:设置新任务会自动取消上一次,替代 Handler 的 removeCallbacks + postDelayed
*/
private final SerialDisposable mRegisterRetry = new SerialDisposable();
/**
* 别名重试任务,同一时刻只保留一个待执行任务
*/
private final SerialDisposable mAliasRetry = new SerialDisposable();
/**
* 标签重试任务,同一时刻只保留一个待执行任务
*/
private final SerialDisposable mTagRetry = new SerialDisposable();
/**
* 定时状态检测流:release 时取消,start 时重新挂上
*/
private final SerialDisposable mStatusCheck = new SerialDisposable();
/**
* SDK 初始化锁,只包住初始化动作,不包住任何网络请求
@@ -109,21 +129,6 @@ public class AliyunPushManager {
private int mAliasRetryCount;
private int mTagRetryCount;
private final Runnable mRegisterTask = this::register;
private final Runnable mAliasTask = this::bindAlias;
private final Runnable mTagTask = this::doBindTags;
private final Runnable mStatusCheckTask = new Runnable() {
@Override
public void run() {
Log.d(TAG, "定时状态检测: 开始检查推送通道");
checkChannelStatus();
mHandler.postDelayed(this, STATUS_CHECK_INTERVAL);
}
};
private AliyunPushManager(Context context) {
Context appContext = context.getApplicationContext();
this.mContext = appContext != null ? appContext : context;
@@ -187,8 +192,15 @@ public class AliyunPushManager {
}
initSdk();
register();
mHandler.removeCallbacks(mStatusCheckTask);
mHandler.postDelayed(mStatusCheckTask, STATUS_CHECK_INTERVAL);
// 用 interval 取代 Handler 自递归:首次触发在 STATUS_CHECK_INTERVAL 之后,保持原有节奏
mStatusCheck.set(Observable.interval(
STATUS_CHECK_INTERVAL, STATUS_CHECK_INTERVAL, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> {
Log.d(TAG, "定时状态检测: 开始检查推送通道");
checkChannelStatus();
}, throwable -> Log.e(TAG, "start: 状态检测异常 " + throwable)));
}
/**
@@ -211,10 +223,11 @@ public class AliyunPushManager {
mPendingTags.clear();
service = mPushService;
}
mHandler.removeCallbacks(mRegisterTask);
mHandler.removeCallbacks(mAliasTask);
mHandler.removeCallbacks(mTagTask);
mHandler.removeCallbacks(mStatusCheckTask);
// set(null) 会取消尚未执行的任务,且 SerialDisposable 仍可复用,release 后能再次 start
mRegisterRetry.set(null);
mAliasRetry.set(null);
mTagRetry.set(null);
mStatusCheck.set(null);
if (service == null) {
return;
}
@@ -312,7 +325,7 @@ public class AliyunPushManager {
final CloudPushService service = ensureService();
if (service == null) {
Log.e(TAG, "register: 推送服务不可用,稍后重试");
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
scheduleRetry(mRegisterRetry, this::register, nextRegisterAttempt(), "register");
return;
}
synchronized (this) {
@@ -362,7 +375,8 @@ public class AliyunPushManager {
flushTags();
return;
}
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
scheduleRetry(mRegisterRetry, AliyunPushManager.this::register,
nextRegisterAttempt(), "register");
}
});
} catch (Throwable e) {
@@ -370,7 +384,7 @@ public class AliyunPushManager {
mRegistering = false;
}
Log.e(TAG, "register: 注册异常 " + e.getMessage());
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
scheduleRetry(mRegisterRetry, this::register, nextRegisterAttempt(), "register");
}
}
@@ -405,7 +419,7 @@ public class AliyunPushManager {
if (snEmpty) {
// sn 可能尚未就绪,走退避重试而不是直接放弃
Log.e(TAG, "bindAlias: sn 为空,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "bindAlias");
return;
}
final CloudPushService service = ensureService();
@@ -414,7 +428,7 @@ public class AliyunPushManager {
mBindingAlias = false;
}
Log.e(TAG, "bindAlias: 推送服务不可用,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "bindAlias");
return;
}
try {
@@ -436,7 +450,7 @@ public class AliyunPushManager {
mBindingAlias = false;
}
Log.e(TAG, "bindAlias: 绑定账号异常 " + e.getMessage());
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "bindAlias");
}
}
@@ -447,7 +461,7 @@ public class AliyunPushManager {
mBindingAlias = false;
}
Log.e(TAG, "addAlias: 推送服务不可用,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "addAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "addAlias");
return;
}
try {
@@ -474,7 +488,7 @@ public class AliyunPushManager {
mBindingAlias = false;
}
Log.e(TAG, "addAlias: 添加别名异常 " + e.getMessage());
scheduleRetry(mAliasTask, nextAliasAttempt(), "addAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "addAlias");
}
}
@@ -498,7 +512,7 @@ public class AliyunPushManager {
register();
return;
}
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
scheduleRetry(mAliasRetry, this::bindAlias, nextAliasAttempt(), "bindAlias");
}
/**
@@ -564,7 +578,7 @@ public class AliyunPushManager {
mBindingTag = false;
}
Log.e(TAG, "doBindTags: 推送服务不可用,稍后重试");
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
scheduleRetry(mTagRetry, this::doBindTags, nextTagAttempt(), "bindTag");
return;
}
try {
@@ -597,7 +611,8 @@ public class AliyunPushManager {
register();
return;
}
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
scheduleRetry(mTagRetry, AliyunPushManager.this::doBindTags,
nextTagAttempt(), "bindTag");
}
});
} catch (Throwable e) {
@@ -606,7 +621,7 @@ public class AliyunPushManager {
mTagsBound = false;
}
Log.e(TAG, "doBindTags: 绑定标签异常 " + e.getMessage());
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
scheduleRetry(mTagRetry, this::doBindTags, nextTagAttempt(), "bindTag");
}
}
@@ -712,11 +727,12 @@ public class AliyunPushManager {
* 统计窗口内失败次数达到上限后暂停定时重试,避免极端网络下形成长尾重试风暴,
* 之后由定时/联网触发的状态检测恢复。
*
* @param target 对应任务的容器,设置新任务会自动取消上一次重试
* @param task 重试任务
* @param attempt 当前已重试次数
* @param action 任务名,仅用于日志
*/
private void scheduleRetry(Runnable task, int attempt, String action) {
private void scheduleRetry(SerialDisposable target, Runnable task, int attempt, String action) {
if (attempt >= RETRY_DELAYS.length) {
Log.e(TAG, "scheduleRetry: " + action + " 重试次数已达上限(" + RETRY_DELAYS.length + "),等待下次状态检测自愈");
return;
@@ -728,8 +744,18 @@ public class AliyunPushManager {
}
long delay = RETRY_DELAYS[attempt];
Log.d(TAG, "scheduleRetry: " + action + " 失败,将在 " + delay + "ms 后进行第 " + (attempt + 1) + " 次重试");
mHandler.removeCallbacks(task);
mHandler.postDelayed(task, delay);
target.set(delayTask(delay, task));
}
/**
* 延时执行任务:定时器在 IO 线程计时,回调切回主线程,与原有 Handler 的线程约定保持一致
*/
private Disposable delayTask(long delay, Runnable task) {
return Observable.timer(delay, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> task.run(),
throwable -> Log.e(TAG, "delayTask: " + throwable));
}
/**
@@ -23,17 +23,26 @@ import android.view.WindowManager;
import com.android.internal.view.RotationPolicy;
import com.fuying.sn.R;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.local.cache.CacheHelper;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.platform.control.ControlManager;
import com.fuying.sn.platform.system.AndroidSettingsWriter;
import com.fuying.sn.platform.system.DeviceManager;
import com.fuying.sn.platform.time.TimeManager;
import com.fuying.sn.core.common.ui.ToastUtil;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.local.cache.CacheHelper;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.core.data.remote.BackgroundRequests;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.platform.app.ApkUtils;
import com.fuying.sn.platform.app.AppProcessUtils;
import com.fuying.sn.platform.control.ControlManager;
import com.fuying.sn.platform.system.AndroidSettingsWriter;
import com.fuying.sn.platform.system.CmdUtil;
import com.fuying.sn.platform.system.DeviceManager;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.platform.system.SystemUtils;
import com.fuying.sn.platform.time.TimeManager;
import com.fuying.sn.platform.time.TimeUtils;
import com.fuying.sn.runtime.receiver.BootReceiver;
import com.fuying.sn.runtime.service.LogcatService;
import com.fuying.sn.runtime.service.ManagerService;
@@ -44,19 +53,9 @@ import com.fuying.sn.runtime.sync.DeviceProfileSync;
import com.fuying.sn.runtime.sync.DeviceSettingsSync;
import com.fuying.sn.runtime.sync.PushTagSync;
import com.fuying.sn.runtime.sync.RemoteDiagnostics;
import com.fuying.sn.platform.app.ApkUtils;
import com.fuying.sn.platform.system.CmdUtil;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.platform.system.SystemUtils;
import com.fuying.sn.platform.time.TimeUtils;
import com.fuying.sn.core.common.ui.ToastUtil;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import com.fuying.sn.platform.app.AppProcessUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -76,6 +75,8 @@ import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.reactivex.rxjava3.subjects.PublishSubject;
import io.reactivex.rxjava3.subjects.Subject;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
@@ -83,8 +84,6 @@ import okhttp3.RequestBody;
public class PushManager {
private static final String TAG = "PushManager";
@SuppressLint("StaticFieldLeak")
private static volatile PushManager sInstance;
private Context mContext;
@@ -96,6 +95,16 @@ public class PushManager {
}
this.mContext = context.getApplicationContext();
this.mCacheHelper = new CacheHelper(context);
// 常驻单例随进程存活,订阅不主动释放;指定主线程调度器,保证刷新逻辑仍在主线程执行
mDebounceSubject
.debounce(DEBOUNCE_WINDOW, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean ignored) {
Log.e(TAG, "scheduleRefresh -> updateUserSettings");
updateUserSettings();
}
});
}
/**
@@ -158,13 +167,11 @@ public class PushManager {
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
private final Runnable mRefreshTask = this::runUserSettingsRefresh;
private final Runnable mDebounceRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, "scheduleRefresh -> updateUserSettings");
updateUserSettings();
}
};
/**
* 推送防抖入口:窗口内多条推送合并为一次刷新。
* 推送回调可能来自不同线程,用 toSerialized 保证并发 onNext 安全。
*/
private final Subject<Boolean> mDebounceSubject = PublishSubject.<Boolean>create().toSerialized();
private final Handler mUpgradeHandler = new Handler(Looper.getMainLooper());
private final Runnable mResumeUpgrade = this::runPendingUpgrade;
@@ -1265,8 +1272,7 @@ public class PushManager {
* 多条推送在 {@link #DEBOUNCE_WINDOW} 内到达只合并为一次刷新。
*/
public void scheduleRefresh() {
mMainHandler.removeCallbacks(mDebounceRunnable);
mMainHandler.postDelayed(mDebounceRunnable, DEBOUNCE_WINDOW);
mDebounceSubject.onNext(true);
}
/**
@@ -1,16 +1,12 @@
package com.fuying.sn.runtime.receiver;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.common.rx.RxSchedulers;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.platform.app.ApkUtils;
import com.fuying.sn.platform.control.ControlManager;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.platform.time.TimeManager;
@@ -21,7 +17,7 @@ import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.subjects.PublishSubject;
public class ApkInstallReceiver extends BroadcastReceiver {
private static final String TAG = "APKinstallReceiver";
private static final String TAG = "ApkInstallReceiver";
/**
* 应用安装、卸载事件流。
@@ -31,16 +27,12 @@ public class ApkInstallReceiver extends BroadcastReceiver {
*/
private static final PublishSubject<String> INSTALL_EVENT = PublishSubject.create();
@SuppressLint("StaticFieldLeak")
private static Context mContext;
static {
sendAppInfo();
}
@Override
public void onReceive(final Context context, Intent intent) {
mContext = context.getApplicationContext();
// 读取安装、卸载或覆盖安装广播的动作。
final String action = intent.getAction();
final String dataString = intent.getDataString();
@@ -54,33 +46,30 @@ public class ApkInstallReceiver extends BroadcastReceiver {
}
private void handleBroadcast(Context context, String action, String dataString) {
JgyUtils.getInstance().cleanLauncherCache();
ControlManager.getInstance().setDefaultApp();
Log.e(TAG, "onReceive: " + "action = " + action);
String state;
Log.e(TAG, "handleBroadcast: action = " + action);
if (TextUtils.isEmpty(action)) {
Log.e(TAG, "onReceive: " + "action is empty ");
Log.e(TAG, "handleBroadcast: action is empty ");
return;
}
String packageName = dataString.replace("package:", "");
String actionDesc;
switch (action) {
case Intent.ACTION_PACKAGE_ADDED:
state = "安装了:";
actionDesc = "安装了:";
JgyUtils.RemoveTask(context, packageName);
JgyUtils.getInstance().putBuiltInApps();
break;
case Intent.ACTION_PACKAGE_REPLACED:
cleanLauncher3Cache();
state = "重装了:";
actionDesc = "重装了:";
break;
case Intent.ACTION_PACKAGE_REMOVED:
state = "卸载了:";
actionDesc = "卸载了:";
break;
default:
state = "未知:";
actionDesc = "未知:";
break;
}
Log.e(TAG, "sendAppInfo: " + state + packageName);
Log.e(TAG, "handleBroadcast: " + actionDesc + packageName);
INSTALL_EVENT.onNext(packageName);
if (JgyUtils.PACKAGE_APPSTORE.equals(packageName)) {
//启动应用市场
@@ -91,22 +80,15 @@ public class ApkInstallReceiver extends BroadcastReceiver {
}
}
private void cleanLauncher3Cache() {
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.launcher3", null);
}
private static void sendAppInfo() {
// 保留原有 60 秒窗口:安装事件停止 60 秒后才触发一次同步,批量安装只同步一次
INSTALL_EVENT.debounce(60, TimeUnit.SECONDS)
.observeOn(RxSchedulers.io())
.subscribe(packageName -> {
Log.e("sendAppInfo", "onNext: " + packageName);
int isLogined = KVStore.decodeInt(CommonConfig.isLogined, 2);
if (isLogined != 2) {
// AppPolicySync.getInstance().getForceInstall();
// AppInventorySync.getInstance().getAppInside();
}
Log.e(TAG, "onNext: " + packageName);
ControlManager.getInstance().setDefaultApp();
TimeManager.getInstance().syncInstalledApps();
}, throwable -> Log.e("sendAppInfo", "onError: " + throwable.getMessage()));
}, throwable -> Log.e(TAG, "onError: " + throwable.getMessage()));
}
}
@@ -22,35 +22,32 @@ import android.widget.TextView;
import com.blankj.utilcode.util.NetworkUtils;
import com.fuying.sn.R;
import com.fuying.sn.core.base.BaseService;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.runtime.push.PushManager;
import com.fuying.sn.runtime.receiver.ApkInstallReceiver;
import com.fuying.sn.runtime.receiver.BootReceiver;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.google.gson.JsonObject;
import com.tuo.customview.VerificationCodeView;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.subjects.PublishSubject;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.subjects.PublishSubject;
public class ManagerService extends BaseService implements NetworkUtils.OnNetworkStatusChangedListener {
private final DeviceRepository mRepository = DeviceRepository.getInstance();
private static final String TAG = "ManagerService";
public static final String ACTION_LOCK = "LockScreenReceiver_lockscreen";
public static final String ACTION_UNLOCK = "LockScreenReceiver_unlockscreen";
private static final String DEFAULT_PASSWORD = "0000";
@@ -490,11 +487,11 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
setLockedState(is_screen_lock);
}
private ApkInstallReceiver apKinstallReceiver;
private ApkInstallReceiver apkInstallReceiver;
private void registAppReceive() {
if (null == apKinstallReceiver) {
apKinstallReceiver = new ApkInstallReceiver();
if (null == apkInstallReceiver) {
apkInstallReceiver = new ApkInstallReceiver();
}
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
@@ -502,7 +499,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
ReceiverCompat.registerReceiver(this, apKinstallReceiver, filter, ReceiverCompat.RECEIVER_NOT_EXPORTED);
ReceiverCompat.registerReceiver(this, apkInstallReceiver, filter, ReceiverCompat.RECEIVER_NOT_EXPORTED);
}
private BootReceiver bootReceiver;
@@ -528,8 +525,8 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
if (null != lockScreenReceiver) {
ReceiverCompat.unregisterReceiver(this, lockScreenReceiver);
}
if (null != apKinstallReceiver) {
ReceiverCompat.unregisterReceiver(this, apKinstallReceiver);
if (null != apkInstallReceiver) {
ReceiverCompat.unregisterReceiver(this, apkInstallReceiver);
}
if (null != bootReceiver) {
ReceiverCompat.unregisterReceiver(this, bootReceiver);
@@ -15,15 +15,16 @@ import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleService;
import com.blankj.utilcode.util.NetworkUtils;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import com.fuying.sn.core.common.system.ReceiverCompat;
import com.fuying.sn.platform.system.SystemUtils;
import com.fuying.sn.platform.time.TimeUtils;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import com.google.gson.JsonObject;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
@@ -43,7 +44,7 @@ import okhttp3.WebSocketListener;
* DESTROYED 之后不再有任何连接动作。不再依赖 Service 自身回调去手动管理生命周期。
*
* <p>连接状态(mConnecting / mOpened / mWebSocket)只在主线程读写:OkHttp 回调和网络
* 状态回调都先切回主线程,心跳流和错峰任务也通过 observeOn 回到主线程。这样建连、
* 状态回调都先切回主线程,心跳流和错峰任务直接指定主线程调度器。这样建连、
* 关闭、失败回调天然串行,不会出现两个线程同时建连或状态互相覆盖。
*
* <p>连接时机沿用屏幕状态策略:亮屏广播触发重连,息屏广播主动断开并取消在途任务,
@@ -254,9 +255,8 @@ public class SocketService extends LifecycleService implements NetworkUtils.OnNe
return;
}
mHeartBeatDisposables.clear();
mHeartBeatDisposables.add(Observable.interval(0, HEART_BEAT_RATE, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
mHeartBeatDisposables.add(Observable.interval(0, HEART_BEAT_RATE, TimeUnit.MILLISECONDS,
AndroidSchedulers.mainThread())
.subscribe(tick -> checkConnection(),
throwable -> Log.e(TAG, "startHeartBeat: " + throwable)));
Log.e(TAG, "startHeartBeat: 已开启心跳检测");
@@ -346,10 +346,9 @@ public class SocketService extends LifecycleService implements NetworkUtils.OnNe
}
long delay = TimeUtils.randomDelay(RECONNECT_JITTER_MIN, RECONNECT_JITTER_MAX);
Log.e(TAG, "scheduleNetworkReconnect: 网络恢复, 错峰延时 = " + delay);
mReconnectDisposable.set(Observable.timer(delay, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> checkConnection(),
mReconnectDisposable.set(Completable.timer(delay, TimeUnit.MILLISECONDS,
AndroidSchedulers.mainThread())
.subscribe(() -> checkConnection(),
throwable -> Log.e(TAG, "scheduleNetworkReconnect: " + throwable)));
}
@@ -8,32 +8,29 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import com.fuying.sn.platform.system.AndroidSettingsWriter;
import android.text.TextUtils;
import android.util.Log;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.data.dto.app.AppAndWhiteBean;
import com.fuying.sn.core.data.dto.app.AppInfo;
import com.fuying.sn.core.data.dto.app.AppJump;
import com.fuying.sn.core.data.dto.app.AppStart;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.dto.app.BlacklistBean;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.local.cache.CacheHelper;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.core.data.remote.BackgroundRequests;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.runtime.sync.RequestCallbacks.CompleteCallback;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.platform.app.ApkUtils;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.platform.control.AppWhitelistUtils;
import com.fuying.sn.platform.system.AndroidSettingsWriter;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.runtime.sync.RequestCallbacks.CompleteCallback;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;