refactor(push): 推送调用收口到 AliyunPushManager 并在联网后自检通道

新增统一管理器负责初始化、注册、别名、标签、退避重试与通道保活;BaseApplication/PushTagSync 不再直连 SDK;MainService 网络恢复时检查通道状态。
This commit is contained in:
tongtong committed 2026-11-12 17:06:19 +08:00
1 parent 01dc9e2537
commit 036623a06a
9 files changed
+988 -269

No files matched your search

@@ -6,12 +6,8 @@ import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.arialyy.aria.core.Aria;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.core.common.sync.DeviceSyncGateways;
@@ -24,6 +20,7 @@ import com.fuying.sn.platform.location.AmapManager;
import com.fuying.sn.platform.control.ControlManager;
import com.fuying.sn.platform.system.DeviceManager;
import com.fuying.sn.platform.time.TimeManager;
import com.fuying.sn.runtime.push.AliyunPushManager;
import com.fuying.sn.runtime.push.PushManager;
import com.fuying.sn.core.data.local.db.log.LogDBManager;
import com.fuying.sn.runtime.service.DownloadService;
@@ -50,6 +47,8 @@ import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import com.fuying.sn.platform.control.ControlPanelManager;
import java.util.Collections;
public class BaseApplication extends Application {
private static final String TAG = "BaseApplication";
@@ -238,73 +237,10 @@ public class BaseApplication extends Application {
}
private void aliyunPushInit() {
// PushInitConfig pushInitConfig = new PushInitConfig.Builder()
// .application(this)
// // 开启channel进程
// .disableChannelProcess(true)
// // 开启channel进程心跳
// .disableChannelProcessHeartbeat(true)
// .build();
//
// PushServiceFactory.init(pushInitConfig);
PushServiceFactory.init(this);
CloudPushService pushService = PushServiceFactory.getCloudPushService();
// pushService.setPushIntentService(AliMessageIntentService.class);
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.register(this, new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.e("AliyunPush", "init cloudchannel success");
Log.e("AliyunPush", "init cloudchannel success " + pushService.getDeviceId());
String sn = DeviceIdUtils.getSerial();
Log.e(TAG, "AliyunPush: sn=" + sn);
if (TextUtils.isEmpty(sn)) {
return;
}
pushService.bindAccount(sn, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.e("AliyunPush", "bind account " + sn + " success\n");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e("AliyunPush", "bind account " + sn + " failed." +
"errorCode: " + errorCode + ", errorMsg:" + errorMsg);
}
});
pushService.addAlias(sn, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.e("AliyunPush", "add alias " + sn + " success\n");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e("AliyunPush", "add alias " + sn + " failed." +
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
}
});
pushService.bindTag(CloudPushService.DEVICE_TARGET, new String[]{BuildConfig.platform}, null, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.e("AliyunPush", "add tag " + sn + " success\n");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e("AliyunPush", "add tag " + sn + " failed." +
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
}
});
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.e("AliyunPush", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
// 推送的初始化、注册、别名与标签全部交由 AliyunPushManager 统一处理
AliyunPushManager.init(this);
// 机型标签先挂起,注册成功后由管理器自动补齐
AliyunPushManager.getInstance().bindTags(Collections.singleton(BuildConfig.platform));
}
}
@@ -0,0 +1,30 @@
package com.fuying.sn.core.common.rx;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.schedulers.Schedulers;
/**
* 全局 RxJava 调度器入口。
*
* <p>统一复用 RxJava 内置调度器,业务代码不再手动创建线程池,
* 避免线程数量失控和重复封装。
*/
public final class RxSchedulers {
private RxSchedulers() {
}
/**
* 串行调度器:所有任务共用同一条线程,并按提交顺序依次执行。
*/
public static Scheduler serial() {
return Schedulers.single();
}
/**
* IO 调度器:用于网络、文件等阻塞型任务。
*/
public static Scheduler io() {
return Schedulers.io();
}
}
@@ -0,0 +1,748 @@
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;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushInitConfig;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.fuying.sn.core.common.device.DeviceIdUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 阿里云移动推送统一管理类。
* <p>
* 职责:
* 1. 初始化 PushServiceFactory(含通道定时保活);
* 2. 注册设备、绑定账号(别名)与标签;
* 3. 失败自动重试(指数退避,退避用尽后由状态检测兜底);
* 4. 定时 / 主动状态检测(checkChannelStatus),通道关闭时自动重新初始化并注册。
* <p>
* 所有推送 SDK 调用统一收口到本类,业务层不要再直接调用 PushServiceFactory.getCloudPushService()。
* <p>
* 线程约定:状态位统一在 synchronized(this) 内翻转,SDK 调用一律在锁外发起,
* 避免 SDK 回调线程阻塞在状态锁上导致互相等待。
*/
public class AliyunPushManager {
private static final String TAG = "AliyunPushManager";
/**
* 设备已经注册成功,无需重复注册
*/
public static final String CODE_ALREADY_REGISTERED = "PUSH_20110";
/**
* 设备未注册 / 账号未绑定,需要重新走注册流程
*/
public static final String CODE_NOT_REGISTERED = "PUSH_20101";
/**
* 通道保活间隔,SDK 内部定时拉起通道
*/
private static final int LOOP_CHANNEL_INTERVAL = 10 * 60 * 1000;
/**
* 状态检测间隔
*/
private static final long STATUS_CHECK_INTERVAL = 30 * 60 * 1000L;
/**
* 重试熔断统计窗口:窗口内失败达到上限就暂停定时重试,交给状态检测自愈
*/
private static final long FAILURE_WINDOW = 10 * 60 * 1000L;
/**
* 窗口内允许的最大失败次数
*/
private static final int MAX_FAILURES_IN_WINDOW = 3;
/**
* 重试间隔(指数退避),数组长度即单个任务的最大重试次数
*/
private static final long[] RETRY_DELAYS = {
5 * 1000L,
10 * 1000L,
30 * 1000L,
60 * 1000L,
2 * 60 * 1000L,
5 * 60 * 1000L
};
private static volatile AliyunPushManager sInstance;
private final Context mContext;
private final Application mApplication;
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* SDK 初始化锁,只包住初始化动作,不包住任何网络请求
*/
private final Object mInitLock = new Object();
/**
* 最近的失败时间点,用于重试熔断(跨注册/别名/标签共用,防止极端网络下重试风暴)
*/
private final List<Long> mFailureTimes = new ArrayList<>();
/**
* 待绑定的标签,注册成功后自动补齐
*/
private final Set<String> mPendingTags = new LinkedHashSet<>();
private volatile CloudPushService mPushService;
private volatile boolean mRegistered;
private boolean mStarted;
private boolean mRegistering;
private boolean mBindingAlias;
private boolean mAliasBound;
private boolean mBindingTag;
/**
* 标签已绑定成功标记:避免状态检测每 30 分钟重复 bindTag
*/
private boolean mTagsBound;
private int mRegisterRetryCount;
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;
this.mApplication = mContext instanceof Application ? (Application) mContext : null;
}
/**
* 初始化并启动推送(幂等)
*/
public static void init(Context context) {
if (context == null) {
Log.e(TAG, "init: context is null");
return;
}
if (sInstance == null) {
synchronized (AliyunPushManager.class) {
if (sInstance == null) {
sInstance = new AliyunPushManager(context);
}
}
}
sInstance.start();
}
public static AliyunPushManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException("You must be init AliyunPushManager first");
}
return sInstance;
}
/**
* 获取设备 deviceId,SDK 未初始化或异常时返回空串
*/
public static String getDeviceId() {
try {
AliyunPushManager manager = sInstance;
CloudPushService service = manager != null && manager.mPushService != null
? manager.mPushService
: PushServiceFactory.getCloudPushService();
if (service == null) {
return "";
}
String deviceId = service.getDeviceId();
return deviceId == null ? "" : deviceId;
} catch (Throwable e) {
Log.e(TAG, "getDeviceId: " + e.getMessage());
return "";
}
}
/**
* 启动推送:初始化 SDK -> 注册设备 -> 开启状态检测
*/
public void start() {
synchronized (this) {
if (mStarted) {
return;
}
mStarted = true;
}
initSdk();
register();
mHandler.removeCallbacks(mStatusCheckTask);
mHandler.postDelayed(mStatusCheckTask, STATUS_CHECK_INTERVAL);
}
/**
* 停止推送:清空定时任务、复位状态位,并解绑账号、关闭推送通道
*/
public void release() {
final CloudPushService service;
synchronized (this) {
mStarted = false;
mRegistered = false;
mRegistering = false;
mAliasBound = false;
mBindingAlias = false;
mBindingTag = false;
mTagsBound = false;
mRegisterRetryCount = 0;
mAliasRetryCount = 0;
mTagRetryCount = 0;
mFailureTimes.clear();
mPendingTags.clear();
service = mPushService;
}
mHandler.removeCallbacks(mRegisterTask);
mHandler.removeCallbacks(mAliasTask);
mHandler.removeCallbacks(mTagTask);
mHandler.removeCallbacks(mStatusCheckTask);
if (service == null) {
return;
}
try {
// 仅清定时任务不会让 SDK 下线,必须解绑账号并关闭通道
service.unbindAccount(new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.d(TAG, "release: 解绑账号成功");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e(TAG, "release: 解绑账号失败,errorCode = " + errorCode + ", errorMsg = " + errorMsg);
}
});
service.turnOffPushChannel(new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.d(TAG, "release: 关闭推送通道成功");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e(TAG, "release: 关闭推送通道失败,errorCode = " + errorCode + ", errorMsg = " + errorMsg);
}
});
} catch (Throwable e) {
Log.e(TAG, "release: 停止推送异常 " + e.getMessage());
}
}
private void initSdk() {
if (mApplication == null) {
Log.e(TAG, "initSdk: application is null");
return;
}
synchronized (mInitLock) {
try {
// 特殊场景 需要定时拉起 channel
PushInitConfig config = new PushInitConfig.Builder()
.application(mApplication)
.loopStartChannel(true)
.loopInterval(LOOP_CHANNEL_INTERVAL)
.build();
PushServiceFactory.init(config);
CloudPushService service = PushServiceFactory.getCloudPushService();
if (service != null) {
service.setLogLevel(CloudPushService.LOG_DEBUG);
}
mPushService = service;
Log.d(TAG, "initSdk: 初始化成功");
} catch (Throwable e) {
mPushService = null;
Log.e(TAG, "initSdk: 初始化失败 " + e.getMessage());
}
}
}
/**
* 获取推送服务实例,未初始化或初始化失败时返回 null
*/
private CloudPushService ensureService() {
CloudPushService service = mPushService;
if (service != null) {
return service;
}
initSdk();
return mPushService;
}
/**
* 注册设备(幂等,失败自动重试)
*/
public void register() {
boolean needStart;
boolean alreadyRegistered;
synchronized (this) {
needStart = !mStarted;
alreadyRegistered = !needStart && mRegistered;
if (!needStart && !alreadyRegistered && mRegistering) {
Log.d(TAG, "register: 正在注册,忽略本次调用");
return;
}
}
if (needStart) {
start();
return;
}
if (alreadyRegistered) {
bindAlias();
flushTags();
return;
}
final CloudPushService service = ensureService();
if (service == null) {
Log.e(TAG, "register: 推送服务不可用,稍后重试");
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
return;
}
synchronized (this) {
if (!mStarted) {
Log.d(TAG, "register: 已停止,忽略本次注册");
return;
}
if (mRegistering) {
return;
}
mRegistering = true;
}
try {
service.register(mContext, new CommonCallback() {
@Override
public void onSuccess(String response) {
synchronized (AliyunPushManager.this) {
mRegistering = false;
mRegistered = true;
mRegisterRetryCount = 0;
mFailureTimes.clear();
}
Log.d(TAG, "register: 注册成功,deviceId = " + getDeviceId());
bindAlias();
flushTags();
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.e(TAG, "register: 注册失败,errorCode = " + errorCode + ", errorMessage = " + errorMessage);
boolean alreadyRegisteredByCode = CODE_ALREADY_REGISTERED.equals(errorCode);
synchronized (AliyunPushManager.this) {
mRegistering = false;
if (alreadyRegisteredByCode) {
//设备已注册,继续绑定别名与标签即可
mRegistered = true;
mRegisterRetryCount = 0;
mFailureTimes.clear();
} else {
mRegistered = false;
// 重新注册成功后需要重新下发一次标签
mTagsBound = false;
}
}
if (alreadyRegisteredByCode) {
bindAlias();
flushTags();
return;
}
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
}
});
} catch (Throwable e) {
synchronized (this) {
mRegistering = false;
}
Log.e(TAG, "register: 注册异常 " + e.getMessage());
scheduleRetry(mRegisterTask, nextRegisterAttempt(), "register");
}
}
/**
* 绑定账号与别名(设备序列号 SN),失败自动重试
*/
public void bindAlias() {
final String sn = DeviceIdUtils.getSerial();
boolean needRegister;
boolean snEmpty = false;
synchronized (this) {
if (!mStarted) {
Log.d(TAG, "bindAlias: 已停止,忽略本次绑定");
return;
}
needRegister = !mRegistered;
if (!needRegister) {
if (mAliasBound || mBindingAlias) {
return;
}
if (TextUtils.isEmpty(sn)) {
snEmpty = true;
} else {
mBindingAlias = true;
}
}
}
if (needRegister) {
register();
return;
}
if (snEmpty) {
// sn 可能尚未就绪,走退避重试而不是直接放弃
Log.e(TAG, "bindAlias: sn 为空,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
return;
}
final CloudPushService service = ensureService();
if (service == null) {
synchronized (this) {
mBindingAlias = false;
}
Log.e(TAG, "bindAlias: 推送服务不可用,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
return;
}
try {
service.bindAccount(sn, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.d(TAG, "bindAlias: 绑定账号成功 sn = " + sn);
addAlias(sn);
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e(TAG, "bindAlias: 绑定账号失败,errorCode = " + errorCode + ", errorMsg = " + errorMsg);
onAliasFailed(errorCode);
}
});
} catch (Throwable e) {
synchronized (this) {
mBindingAlias = false;
}
Log.e(TAG, "bindAlias: 绑定账号异常 " + e.getMessage());
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
}
}
private void addAlias(final String sn) {
final CloudPushService service = ensureService();
if (service == null) {
synchronized (this) {
mBindingAlias = false;
}
Log.e(TAG, "addAlias: 推送服务不可用,稍后重试");
scheduleRetry(mAliasTask, nextAliasAttempt(), "addAlias");
return;
}
try {
service.addAlias(sn, new CommonCallback() {
@Override
public void onSuccess(String s) {
synchronized (AliyunPushManager.this) {
mBindingAlias = false;
mAliasBound = true;
mAliasRetryCount = 0;
mFailureTimes.clear();
}
Log.d(TAG, "addAlias: 添加别名成功 sn = " + sn);
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e(TAG, "addAlias: 添加别名失败,errorCode = " + errorCode + ", errorMsg = " + errorMsg);
onAliasFailed(errorCode);
}
});
} catch (Throwable e) {
synchronized (this) {
mBindingAlias = false;
}
Log.e(TAG, "addAlias: 添加别名异常 " + e.getMessage());
scheduleRetry(mAliasTask, nextAliasAttempt(), "addAlias");
}
}
/**
* 别名绑定失败统一处理:未注册错误码直接重新注册,其它错误退避重试
*/
private void onAliasFailed(String errorCode) {
boolean notRegistered = CODE_NOT_REGISTERED.equals(errorCode);
synchronized (this) {
mBindingAlias = false;
mAliasBound = false;
if (notRegistered) {
mRegistered = false;
mRegisterRetryCount = 0;
// 重新注册成功后需要重新下发一次标签
mTagsBound = false;
}
}
if (notRegistered) {
Log.e(TAG, "onAliasFailed: 设备未注册,重新注册");
register();
return;
}
scheduleRetry(mAliasTask, nextAliasAttempt(), "bindAlias");
}
/**
* 绑定标签,失败自动重试;设备未注册时先注册,注册成功后自动补齐
*/
public void bindTags(Set<String> tagSets) {
if (tagSets == null) {
return;
}
synchronized (this) {
mPendingTags.clear();
mPendingTags.addAll(tagSets);
mTagsBound = false;
}
flushTags();
}
private void flushTags() {
boolean hasPending;
synchronized (this) {
hasPending = !mPendingTags.isEmpty();
}
if (hasPending) {
doBindTags();
}
}
private void doBindTags() {
boolean needRegister = false;
String[] tag = null;
synchronized (this) {
if (!mStarted) {
Log.d(TAG, "doBindTags: 已停止,忽略本次绑定");
return;
}
if (!mRegistered) {
needRegister = true;
} else if (mBindingTag) {
Log.d(TAG, "doBindTags: 正在绑定,忽略本次调用");
return;
} else if (mPendingTags.isEmpty()) {
return;
} else if (mTagsBound) {
// 标签已绑定成功,状态检测时不再重复下发
return;
} else {
tag = mPendingTags.toArray(new String[0]);
// 状态位与取标签在同一把锁内完成,避免并发重复绑定
mBindingTag = true;
}
}
if (needRegister) {
register();
return;
}
if (tag == null) {
return;
}
final String[] finalTag = tag;
final CloudPushService service = ensureService();
if (service == null) {
synchronized (this) {
mBindingTag = false;
}
Log.e(TAG, "doBindTags: 推送服务不可用,稍后重试");
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
return;
}
try {
service.bindTag(CloudPushService.DEVICE_TARGET, finalTag, null, new CommonCallback() {
@Override
public void onSuccess(String s) {
synchronized (AliyunPushManager.this) {
mBindingTag = false;
mTagsBound = true;
mTagRetryCount = 0;
}
Log.d(TAG, "doBindTags: 绑定标签成功 " + Arrays.toString(finalTag));
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e(TAG, "doBindTags: 绑定标签失败 " + Arrays.toString(finalTag)
+ ", errorCode = " + errorCode + ", errorMsg = " + errorMsg);
boolean notRegistered;
synchronized (AliyunPushManager.this) {
mBindingTag = false;
mTagsBound = false;
notRegistered = CODE_NOT_REGISTERED.equals(errorCode);
if (notRegistered) {
mRegistered = false;
mRegisterRetryCount = 0;
}
}
if (notRegistered) {
register();
return;
}
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
}
});
} catch (Throwable e) {
synchronized (this) {
mBindingTag = false;
mTagsBound = false;
}
Log.e(TAG, "doBindTags: 绑定标签异常 " + e.getMessage());
scheduleRetry(mTagTask, nextTagAttempt(), "bindTag");
}
}
/**
* 检测推送通道状态,通道关闭或未注册时自动重新初始化并注册。
* 可用于开机、亮屏、网络恢复等时机主动调用。
*/
public void checkChannelStatus() {
boolean needStart;
synchronized (this) {
needStart = !mStarted;
}
if (needStart) {
start();
return;
}
final CloudPushService service = ensureService();
if (service == null) {
Log.e(TAG, "checkChannelStatus: 推送服务不可用,重新注册");
register();
return;
}
try {
service.checkPushChannelStatus(new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.d(TAG, "checkChannelStatus: onSuccess = " + response);
if ("on".equals(response)) {
//通道正常,自愈注册 / 别名 / 标签
boolean needRegister;
boolean needAlias;
boolean needTag;
synchronized (AliyunPushManager.this) {
needRegister = !mRegistered;
needAlias = !needRegister && !mAliasBound && !mBindingAlias;
needTag = !needRegister && !mPendingTags.isEmpty() && !mBindingTag && !mTagsBound;
}
if (needRegister) {
Log.e(TAG, "checkChannelStatus: 通道正常但设备未注册,重新注册");
register();
return;
}
if (needAlias) {
bindAlias();
}
if (needTag) {
doBindTags();
}
return;
}
//通道关闭,重新初始化并注册
Log.e(TAG, "checkChannelStatus: 推送通道已关闭,重新初始化并注册");
synchronized (AliyunPushManager.this) {
mRegistered = false;
mRegisterRetryCount = 0;
mAliasBound = false;
// 重新注册后设备标识可能变化,标签需要重新下发一次
mTagsBound = false;
}
initSdk();
register();
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.e(TAG, "checkChannelStatus: 检查失败,errorCode = " + errorCode
+ ", errorMessage = " + errorMessage);
boolean needRegister;
synchronized (AliyunPushManager.this) {
needRegister = !mRegistered;
}
if (needRegister) {
register();
}
}
});
} catch (Throwable e) {
Log.e(TAG, "checkChannelStatus: 检查通道异常 " + e.getMessage());
}
}
/**
* @return 设备是否已注册成功
*/
public boolean isRegistered() {
return mRegistered;
}
private synchronized int nextRegisterAttempt() {
return mRegisterRetryCount++;
}
private synchronized int nextAliasAttempt() {
return mAliasRetryCount++;
}
private synchronized int nextTagAttempt() {
return mTagRetryCount++;
}
/**
* 指数退避重试,并做熔断保护:
* 统计窗口内失败次数达到上限后暂停定时重试,避免极端网络下形成长尾重试风暴,
* 之后由定时/联网触发的状态检测恢复。
*
* @param task 重试任务
* @param attempt 当前已重试次数
* @param action 任务名,仅用于日志
*/
private void scheduleRetry(Runnable task, int attempt, String action) {
if (attempt >= RETRY_DELAYS.length) {
Log.e(TAG, "scheduleRetry: " + action + " 重试次数已达上限(" + RETRY_DELAYS.length + "),等待下次状态检测自愈");
return;
}
if (recordFailureAndCheckCircuit()) {
Log.e(TAG, "scheduleRetry: " + action + " 近 " + (FAILURE_WINDOW / 60000L) + " 分钟失败已达 "
+ MAX_FAILURES_IN_WINDOW + " 次,暂停定时重试,等待状态检测自愈");
return;
}
long delay = RETRY_DELAYS[attempt];
Log.d(TAG, "scheduleRetry: " + action + " 失败,将在 " + delay + "ms 后进行第 " + (attempt + 1) + " 次重试");
mHandler.removeCallbacks(task);
mHandler.postDelayed(task, delay);
}
/**
* 记录一次失败,并判断是否触发熔断
*
* @return true 表示窗口内失败次数已达上限,本次不再安排重试
*/
private synchronized boolean recordFailureAndCheckCircuit() {
long now = System.currentTimeMillis();
while (!mFailureTimes.isEmpty() && now - mFailureTimes.get(0) > FAILURE_WINDOW) {
mFailureTimes.remove(0);
}
mFailureTimes.add(now);
return mFailureTimes.size() >= MAX_FAILURES_IN_WINDOW;
}
}
@@ -14,6 +14,7 @@ import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
@@ -84,7 +85,7 @@ public class PushManager {
private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
@SuppressLint("StaticFieldLeak")
private static PushManager sInstance;
private static volatile PushManager sInstance;
private Context mContext;
private CacheHelper mCacheHelper;
@@ -100,17 +101,17 @@ public class PushManager {
* 推送防抖窗口:短时间内连续多条推送,合并为一次刷新。
*/
private static final long DEBOUNCE_WINDOW = 3 * 1000L;
/**
* 推送触发刷新的短节流 key(1 分钟内因推送触发的多次刷新只真正请求一次)。
*/
private static final String KEY_PUSH_REFRESH = "push_config_refresh";
/**
* 推送是全量下发,所有设备几乎同一时刻收到并触发刷新,
* 这里在原有延时上再叠加 [0, 30s) 的随机抖动,避免整批设备集中请求把服务端打挂。
*/
private static final long PUSH_REFRESH_JITTER = 30 * 1000L;
/**
* 刷新请求的基础延时,叠加随机抖动后真正发起请求。
*/
private static final long REFRESH_BASE_DELAY = 2345L;
/**
* 自身升级包的下载错峰上限:窗口内最多随机延后 1 小时才开始下载升级包。
* 自身升级会导致全量设备重启并在重启后集中请求,所以错峰窗口要足够长。
@@ -138,16 +139,43 @@ public class PushManager {
*/
private boolean mUpgradeScheduled = false;
private Handler mSyncHandler;
private Runnable mDebounceRunnable;
/**
* 已安排但尚未执行的刷新请求标记:防抖刷新与 case 内的直接刷新共用同一个任务,
* 避免同一条推送触发两轮完整同步。
*/
private boolean mRefreshScheduled = false;
/**
* 待执行的刷新是否需要作废 SN 缓存,多次请求合并时按"需要作废"取并集。
*/
private boolean mPendingInvalidateSnInfo = false;
/**
* 上一次真正发起刷新的时刻(单调时钟,避免系统改时间导致比较失真)。
*/
private long mLastRefreshTime = 0;
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();
}
};
private final Handler mUpgradeHandler = new Handler(Looper.getMainLooper());
private final Runnable mResumeUpgrade = this::runPendingUpgrade;
public static void init(Context context) {
if (sInstance == null) {
sInstance = new PushManager(context);
// 初始化完成后恢复已落盘的升级任务。
sInstance.mUpgradeHandler.post(sInstance.mResumeUpgrade);
synchronized (PushManager.class) {
if (sInstance == null) {
sInstance = new PushManager(context);
// 初始化完成后恢复已落盘的升级任务。
sInstance.mUpgradeHandler.post(sInstance.mResumeUpgrade);
}
}
}
}
@@ -300,6 +328,21 @@ public class PushManager {
private static final String PUSH_ADD_APK = "89";
public void setPushContent(String title, String extras) {
if (TextUtils.isEmpty(title)) {
Log.e(TAG, "setPushContent: title 为空,忽略本条推送");
return;
}
try {
dispatchPushContent(title, extras);
} catch (Throwable e) {
// 字段缺失或格式异常的推送都在 SDK 回调线程上,不能让它带崩常驻进程
Log.e(TAG, "setPushContent: 处理推送异常, title = " + title + ", " + e.getMessage(), e);
}
// 无论收到何种推送,都触发一次配置刷新(与其他刷新请求合并,保证最新且不过频)
scheduleRefresh();
}
private void dispatchPushContent(String title, String extras) {
switch (title) {
case PUSH_GET_DRIVELINE:
showDeviceOnlinePush();
@@ -519,9 +562,6 @@ public class PushManager {
break;
default:
}
// 无论收到何种推送,都触发一次配置刷新(防抖+短节流,保证最新且不过频)
scheduleRefresh();
}
private void showDeviceOnlinePush() {
@@ -568,9 +608,6 @@ public class PushManager {
private void setBluetoothState(String jsonString) {
ToastUtil.debugShow("收到推送消息: 蓝牙管控");
if (!TextUtils.isEmpty(jsonString)) {
if (null == mBluetoothAdapter) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//获取默认蓝牙适配器
}
JsonObject extra = GsonUtils.getJsonObject(jsonString);
int is_bluetooth = changeNum(extra.get("setting_bht").getAsInt());
Log.e(TAG, "aole_bht_forbid_on: " + is_bluetooth);
@@ -578,15 +615,11 @@ public class PushManager {
//写入系统数据库
boolean aole_bht_forbid_on = Settings.System.putInt(mContext.getContentResolver(), CommonConfig.AOLE_ACTION_BHT_FORBID_ON, is_bluetooth);
Log.e(TAG, "aole_bht_forbid_on: " + aole_bht_forbid_on);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (aole_bht_forbid_on) {
//成功
if (null == mBluetoothAdapter) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//获取默认蓝牙适配器
}
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 没有蓝牙硬件时不能继续调用 disable,否则会空指针
if (aole_bht_forbid_on && bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
//设置关闭时关闭蓝牙
mBluetoothAdapter.disable();
bluetoothAdapter.disable();
}
} catch (Exception e) {
Log.e(TAG, "setBluetooth: " + e.getMessage());
@@ -600,7 +633,7 @@ public class PushManager {
ToastUtil.debugShow("收到推送消息: 浏览器上网管控");
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.browser", succeeded -> {
//延时2秒执行,以防收到推送数据库还没有生效;清理完成后再同步,避免白名单被清掉
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().setBrowserWhiteList();
@@ -611,7 +644,7 @@ public class PushManager {
private void setAppNetworkState() {
ToastUtil.debugShow("收到推送消息: 应用联网管控");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
AppInventorySync.getInstance().getAppInside();
@@ -778,7 +811,7 @@ public class PushManager {
ToastUtil.debugShow("收到推送消息: 浏览器书签");
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.browser", succeeded -> {
//延时2秒执行,以防收到推送数据库还没有生效;清理完成后再同步,避免书签被清掉
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().getBrowserWhiteList();
@@ -790,7 +823,7 @@ public class PushManager {
private void setAppNetworkAuto() {
ToastUtil.debugShow("收到推送消息: APP联网自启管控");
new Handler(Looper.getMainLooper()).postDelayed(() -> AppInventorySync.getInstance().getAllappPackage(), 2000);
mMainHandler.postDelayed(() -> AppInventorySync.getInstance().getAllappPackage(), 2000);
}
private void handleSystemSettingsPush() {
@@ -805,7 +838,7 @@ public class PushManager {
private void setAppSettings() {
ToastUtil.debugShow("收到推送消息: 获取app管控设置");
new Handler(Looper.getMainLooper()).postDelayed(() -> AppInventorySync.getInstance().getAllappPackage(), 2000);
mMainHandler.postDelayed(() -> AppInventorySync.getInstance().getAllappPackage(), 2000);
}
private void forceKillApp(String extras) {
@@ -1150,7 +1183,7 @@ public class PushManager {
//避免同时请求
int number = random.nextInt(10000);
Log.e(TAG, "addApkToWhiteList: Random " + number);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
AppInventorySync.getInstance().getAppWhiteList(new AppInventorySync.WhiteListCallback() {
@@ -1168,65 +1201,78 @@ public class PushManager {
updateUserSettings(true);
}
/**
* 请求一次配置刷新。
* <p>
* 同一条推送既可能在 case 内直接调用刷新,又会在末尾走统一防抖,
* 这里把多次请求合并到同一个待执行任务上:等待期间只保留一次真正请求,
* "是否需要作废 SN 缓存"按并集处理。
*/
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);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
// 策略推送可能改变 SN 信息。联网恢复沿用正常缓存周期。
if (invalidateSnInfo) {
DeviceRepository.removeCache(UrlAddress.SN_INFO);
}
DeviceProfileSync.getInstance().getSnInfo();
DeviceSettingsSync.getInstance().getSystemSettings();
// 标记只在主线程读写,避免 SDK 回调线程与主线程并发修改
mMainHandler.post(() -> enqueueUserSettingsRefresh(invalidateSnInfo));
}
private void enqueueUserSettingsRefresh(boolean invalidateSnInfo) {
if (invalidateSnInfo) {
mPendingInvalidateSnInfo = true;
}
if (mRefreshScheduled) {
Log.e(TAG, "enqueueUserSettingsRefresh: 已有待执行的刷新,合并本次请求");
return;
}
if (SystemClock.elapsedRealtime() - mLastRefreshTime < DEBOUNCE_WINDOW) {
// 同一条推送里 case 分支的刷新可能已经执行完,此时末尾的防抖刷新要丢弃,
// 否则一次推送仍会跑两轮完整同步。
if (mPendingInvalidateSnInfo) {
mPendingInvalidateSnInfo = false;
DeviceRepository.removeCache(UrlAddress.SN_INFO);
}
Log.e(TAG, "enqueueUserSettingsRefresh: 距上次刷新不足防抖窗口,合并本次请求");
return;
}
mRefreshScheduled = true;
mMainHandler.postDelayed(mRefreshTask,
REFRESH_BASE_DELAY + TimeUtils.randomDelay(0, PUSH_REFRESH_JITTER));
}
private void runUserSettingsRefresh() {
mRefreshScheduled = false;
mLastRefreshTime = SystemClock.elapsedRealtime();
boolean invalidateSnInfo = mPendingInvalidateSnInfo;
mPendingInvalidateSnInfo = false;
// 策略推送可能改变 SN 信息。联网恢复沿用正常缓存周期。
if (invalidateSnInfo) {
DeviceRepository.removeCache(UrlAddress.SN_INFO);
}
DeviceProfileSync.getInstance().getSnInfo();
DeviceSettingsSync.getInstance().getSystemSettings();
// TimePolicySync.getInstance().getAppTimeControl();
// TimePolicySync.getInstance().getMachineTimeControl();
// TimePolicySync.getInstance().getSnTimeControl();
TimeManager.getInstance().refreshTimeControl();
AppInventorySync.getInstance().getAllappPackage();
}
}, 2345 + TimeUtils.randomDelay(0, PUSH_REFRESH_JITTER));
TimeManager.getInstance().refreshTimeControl();
AppInventorySync.getInstance().getAllappPackage();
}
/**
* 推送触发:防抖合并 + 短节流。
* 多条推送在 {@link #DEBOUNCE_WINDOW} 内到达只合并为一次刷新;
* 且 1 分钟内的多次推送触发只真正请求一次,避免推送风暴导致频繁请求接口。
* 推送触发:防抖合并。
* 多条推送在 {@link #DEBOUNCE_WINDOW} 内到达只合并为一次刷新。
*/
public void scheduleRefresh() {
if (mSyncHandler == null) {
mSyncHandler = new Handler(Looper.getMainLooper());
}
if (mDebounceRunnable == null) {
mDebounceRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, "scheduleRefresh -> updateUserSettings");
updateUserSettings();
}
};
}
mSyncHandler.removeCallbacks(mDebounceRunnable);
mSyncHandler.postDelayed(mDebounceRunnable, DEBOUNCE_WINDOW);
mMainHandler.removeCallbacks(mDebounceRunnable);
mMainHandler.postDelayed(mDebounceRunnable, DEBOUNCE_WINDOW);
}
/**
* 立即刷新(绕过防抖,但仍受短节流保护),用于网络恢复、开机完成等场景。
* 立即请求刷新(绕过防抖,但仍与待执行的刷新请求合并),用于网络恢复、开机完成等场景。
*/
public void triggerRefresh() {
if (mSyncHandler == null) {
mSyncHandler = new Handler(Looper.getMainLooper());
}
mSyncHandler.post(new Runnable() {
@Override
public void run() {
Log.e(TAG, "triggerRefresh -> updateUserSettings");
updateUserSettings(false);
}
});
Log.e(TAG, "triggerRefresh -> updateUserSettings");
updateUserSettings(false);
}
private float[] mValues;
@@ -1252,8 +1298,6 @@ public class PushManager {
}
}
private BluetoothAdapter mBluetoothAdapter;
private void intallApk(String jsonString) {
if (TextUtils.isEmpty(jsonString)) {
return;
@@ -1330,7 +1374,7 @@ public class PushManager {
private void downloadWithSpread(JsonObject extra, String url) {
final long delay = TimeUtils.randomDelay(0, OTHER_APP_DOWNLOAD_MAX_SPREAD);
Log.e(TAG, "downloadWithSpread: " + (delay / 1000) + " 秒后开始下载 " + url);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
ApkUtils.ariaDownload(mContext, url, extra);
@@ -1551,7 +1595,12 @@ public class PushManager {
* 避免在链式调用里再嵌套一层 if 判断。
*/
public void doscreenshot() {
String filePath = mContext.getExternalFilesDir("db").getAbsolutePath()
File dbDir = mContext.getExternalFilesDir("db");
if (dbDir == null) {
Log.e(TAG, "doscreenshot: 外部存储不可用,放弃本次截图");
return;
}
String filePath = dbDir.getAbsolutePath()
+ File.separator + DeviceIdUtils.getSerial() + ".png";
getScreenshot(filePath)
.map(code -> {
@@ -69,12 +69,22 @@ public class AliyunMessageReceiver extends MessageReceiver {
Log.e(TAG, "收到一条推送消息 : " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent());
String title = cPushMessage.getTitle();
String content = cPushMessage.getContent();
JsonObject extrasJson = JsonParser.parseString(content).getAsJsonObject();
String extras = "";
if (extrasJson.get("extras") != null) {
extras = extrasJson.get("extras").toString();
// 推送内容由服务端下发,格式异常时不能直接抛出,否则会带崩常驻进程
try {
JsonObject extrasJson = JsonParser.parseString(content).getAsJsonObject();
if (extrasJson.get("extras") != null) {
extras = extrasJson.get("extras").toString();
}
} catch (Throwable e) {
Log.e(TAG, "onMessage: 解析推送内容失败, title = " + title + ", " + e.getMessage(), e);
return;
}
try {
PushManager.getInstance().setPushContent(title, extras);
} catch (Throwable e) {
Log.e(TAG, "onMessage: 分发推送失败, title = " + title + ", " + e.getMessage(), e);
}
PushManager.getInstance().setPushContent(title, extras);
}
/**
@@ -8,6 +8,7 @@ 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.platform.control.ControlManager;
import com.fuying.sn.platform.time.TimeManager;
import com.fuying.sn.platform.app.ApkUtils;
@@ -16,17 +17,22 @@ import com.fuying.sn.core.data.local.prefs.SPUtils;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.subjects.PublishSubject;
public class ApkInstallReceiver extends BroadcastReceiver {
private static final String TAG = "APKinstallReceiver";
/**
* 应用安装、卸载事件流。
*
* <p>广播默认在主线程回调,而清理桌面缓存、设置默认应用、查询下载任务都属于耗时操作,
* 批量安装时容易触发 ANR。事件统一交给 RxJava 串行调度器执行,保持处理顺序不变。
*/
private static final PublishSubject<String> INSTALL_EVENT = PublishSubject.create();
@SuppressLint("StaticFieldLeak")
private static Context mContext;
private static NewAppListener newAppListener;
static {
sendAppInfo();
@@ -36,7 +42,18 @@ public class ApkInstallReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
mContext = context;
// 读取安装、卸载或覆盖安装广播的动作。
String action = intent.getAction();
final String action = intent.getAction();
final String dataString = intent.getDataString();
final PendingResult pendingResult = goAsync();
// 复用 RxJava 串行调度器执行广播逻辑,避免在接收器中手动创建线程池
Completable.fromAction(() -> handleBroadcast(context, action, dataString))
.subscribeOn(RxSchedulers.serial())
.doFinally(pendingResult::finish)
.subscribe(() -> {
}, throwable -> Log.e(TAG, "onReceive: " + throwable.getMessage()));
}
private void handleBroadcast(Context context, String action, String dataString) {
JgyUtils.getInstance().cleanLauncherCache();
ControlManager.getInstance().setDefaultApp();
Log.e(TAG, "onReceive: " + "action = " + action);
@@ -45,7 +62,7 @@ public class ApkInstallReceiver extends BroadcastReceiver {
Log.e(TAG, "onReceive: " + "action is empty ");
return;
}
String packageName = intent.getDataString().replace("package:", "");
String packageName = dataString.replace("package:", "");
switch (action) {
case Intent.ACTION_PACKAGE_ADDED:
state = "安装了:";
@@ -64,7 +81,7 @@ public class ApkInstallReceiver extends BroadcastReceiver {
break;
}
Log.e(TAG, "sendAppInfo: " + state + packageName);
newAppListener.setNewAppListener(packageName);
INSTALL_EVENT.onNext(packageName);
if (JgyUtils.PACKAGE_APPSTORE.equals(packageName)) {
//启动应用市场
// JGYUtils.getInstance().wakeUpDeviceInfo();
@@ -78,39 +95,18 @@ public class ApkInstallReceiver extends BroadcastReceiver {
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.launcher3", null);
}
public interface NewAppListener {
void setNewAppListener(String packageName);
}
private static void sendAppInfo() {
Observable.create((ObservableEmitter<String> emitter) -> newAppListener = emitter::onNext)
.throttleLast(30, TimeUnit.SECONDS)
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
Log.e("sendAppInfo", "onSubscribe: ");
}
@Override
public void onNext(String s) {
Log.e("sendAppInfo", "onNext: " + s);
int isLogined = (int) SPUtils.get(mContext, CommonConfig.isLogined, 2);
if (isLogined != 2) {
// 保留原有 60 秒窗口:安装事件停止 60 秒后才触发一次同步,批量安装只同步一次
INSTALL_EVENT.debounce(60, TimeUnit.SECONDS)
.observeOn(RxSchedulers.io())
.subscribe(packageName -> {
Log.e("sendAppInfo", "onNext: " + packageName);
int isLogined = (int) SPUtils.get(mContext, CommonConfig.isLogined, 2);
if (isLogined != 2) {
// AppPolicySync.getInstance().getForceInstall();
// AppInventorySync.getInstance().getAppInside();
}
TimeManager.getInstance().syncInstalledApps();
}
@Override
public void onError(Throwable e) {
Log.e("sendAppInfo", "onError: " + e.getMessage());
}
@Override
public void onComplete() {
Log.e("sendAppInfo", "onComplete: ");
}
});
TimeManager.getInstance().syncInstalledApps();
}, throwable -> Log.e("sendAppInfo", "onError: " + throwable.getMessage()));
}
}
@@ -39,10 +39,8 @@ import com.tuo.customview.VerificationCodeView;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
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;
@@ -82,23 +80,12 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
}
private interface Start {
void onstar(long time);
}
private Start start;
private final ObservableOnSubscribe<Long> subscribe = new ObservableOnSubscribe<Long>() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
start = new Start() {
@Override
public void onstar(long time) {
emitter.onNext(time);
}
};
}
};
/**
* 服务启动时间事件流。
*
* <p>用 RxJava Subject 直接投递启动时间,替代在 Observable 订阅时保存 emitter 的写法。
*/
private final PublishSubject<Long> startEvent = PublishSubject.create();
private Observer<Long> timeObserver = new Observer<Long>() {
@Override
@@ -117,7 +104,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
@Override
public void onError(Throwable e) {
Log.e("TimeObserver", "onError: " + e.getMessage());
}
@Override
@@ -141,15 +128,14 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
registAppReceive();
registBootReceive();
setFloatingWindow();
Observable.create(subscribe)
.throttleFirst(3, TimeUnit.HOURS)
startEvent.throttleFirst(3, TimeUnit.HOURS)
.subscribe(timeObserver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
start.onstar(System.currentTimeMillis());
startEvent.onNext(System.currentTimeMillis());
return START_STICKY;
}
@@ -40,6 +40,7 @@ import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.core.data.local.db.log.LogDBManager;
import com.fuying.sn.runtime.service.DownloadService;
import com.fuying.sn.runtime.service.SocketService;
import com.fuying.sn.runtime.push.AliyunPushManager;
import com.fuying.sn.runtime.sync.AppInventorySync;
import com.fuying.sn.runtime.sync.AppUsageReporter;
import com.fuying.sn.runtime.sync.DeviceProfileSync;
@@ -57,9 +58,7 @@ import com.tencent.mmkv.MMKV;
import java.io.File;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.subjects.PublishSubject;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.observers.DisposableObserver;
@@ -113,6 +112,8 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
NTPTimeTask task = new NTPTimeTask();
task.execute("ntp.aliyun.com");
// 断网期间推送通道可能已断开,联网后主动检查一次通道状态并自愈注册/别名/标签
AliyunPushManager.getInstance().checkChannelStatus();
scheduleDeviceSync(false);
mMMKV.encode(CommonConfig.DEVICES_REBOOT, false);
@@ -237,8 +238,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
Log.e(TAG, "onCreate: " + e.getMessage());
}
Disposable disposable = Observable.create(configsubscribe)
.throttleLast(15, TimeUnit.SECONDS)
Disposable disposable = configEvent.throttleLast(15, TimeUnit.SECONDS)
.subscribeWith(configObserver);
mDisposables.add(disposable);
versionIsUpdate();
@@ -284,7 +284,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e(TAG, "onStartCommand: " + System.currentTimeMillis());
// configStart.onstar("onStartCommand");
// configEvent.onNext("onStartCommand");
return START_STICKY;
}
@@ -299,18 +299,12 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
AmapManager.getInstance().startLocation();
}
private interface ConfigStart {
void onstar(String key);
}
private ConfigStart configStart;
private ObservableOnSubscribe<String> configsubscribe = new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
configStart = emitter::onNext;
}
};
/**
* 配置刷新事件流。
*
* <p>用 RxJava Subject 直接投递事件,替代在 Observable 订阅时保存 emitter 的写法。
*/
private final PublishSubject<String> configEvent = PublishSubject.create();
private final DisposableObserver<String> configObserver = new DisposableObserver<String>() {
@Override
@@ -321,7 +315,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError: " + e.getMessage());
}
@Override
@@ -3,17 +3,13 @@ package com.fuying.sn.runtime.sync;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.dto.device.SnTag;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.remote.BackgroundRequests;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.runtime.push.AliyunPushManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@@ -72,8 +68,9 @@ public final class PushTagSync {
} else if (platform == JgyUtils.G12NLPlatform) {
set.add(JgyUtils.G12NLTag);
}
// 机型探测是异步回调,标签必须在回调内部合并后再绑定,否则会漏掉机型标签
clearAndAppendTags(set);
});
clearAndAppendTags(set);
}
public void setPushTags(String tag) {
@@ -101,23 +98,9 @@ public final class PushTagSync {
} else if (platform == JgyUtils.G12NLPlatform) {
set.add(JgyUtils.G12NLTag);
}
// 同上:机型标签在异步回调里补齐后再统一绑定
clearAndAppendTags(set);
});
String[] tagSets = new ArrayList<>(set).toArray(new String[set.size()]);
CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.bindTag(CloudPushService.DEVICE_TARGET, tagSets, null, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.e("AliyunPush", "bind tag " + Arrays.toString(tagSets) + " success\n");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e("AliyunPush", "bind tag " + Arrays.toString(tagSets) + " failed." +
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
}
});
}
private void clearAndAppendTags(Set<String> tagSets) {
@@ -127,21 +110,8 @@ public final class PushTagSync {
if (!TextUtils.isEmpty(tag)) {
tagSets.add(tag);
}
String[] set = new ArrayList<>(tagSets).toArray(new String[tagSets.size()]);
CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.bindTag(CloudPushService.DEVICE_TARGET, set, null, new CommonCallback() {
@Override
public void onSuccess(String s) {
Log.e("AliyunPush", "bind tag " + Arrays.toString(set) + " success\n");
}
@Override
public void onFailed(String errorCode, String errorMsg) {
Log.e("AliyunPush", "bind tag " + Arrays.toString(set) + " failed." +
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
}
});
// 推送 SDK 调用统一收口到 AliyunPushManager
AliyunPushManager.getInstance().bindTags(tagSets);
}
});
}