refactor(push): 抽取阿里云推送逻辑至 AliyunPushManager 统一管理
- 新建 AliyunPushManager 类,统一收口推送 SDK 初始化、设备注册、别名/标签绑定 - 实现指数退避重试机制(5s~5min),并加入时间窗内尝试次数熔断防止重试风暴 - 新增定时及主动状态检测(checkChannelStatus),通道关闭时自动重新初始化并注册 - 移除 BaseApplication 中分散的推送相关代码及 RxJava Observable 包装逻辑 - 移除 NetInterfaceManager 中直接调用 PushServiceFactory 的代码,改由管理器代理 - 移除 MainService 中已废弃的 aliyunPushInit 方法,网络恢复时调用状态检测替代 - 所有公共方法入口采用"快照决策→锁外执行"模式,避免持锁等待 SDK 回调导致死锁
This commit is contained in:
1 parent
1ebe19def9
commit
1c844cb8c3
12 files changed
+1200
-510
No files matched your search
+5
-5
@@ -18,8 +18,8 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.aoleyun.sn"
|
||||
versionCode 259
|
||||
versionName "1.6.1105"
|
||||
versionCode 261
|
||||
versionName "1.6.1112"
|
||||
|
||||
//There are no CERT files because If the mini sdk version is 23+, the AGP will ignore the V1 scheme signature.
|
||||
minSdkVersion 24
|
||||
@@ -876,6 +876,8 @@ dependencies {
|
||||
|
||||
implementation files('libs/BaiduTraceSDK_v3_2_2.jar')
|
||||
|
||||
implementation "com.onyx.android.sdk:onyxsdk-device:1.3.5.3"
|
||||
|
||||
// 基础注解库
|
||||
implementation "androidx.annotation:annotation:1.10.0"
|
||||
// 包含 OptIn 实验性 Lint 规则检测的核心库
|
||||
@@ -941,7 +943,7 @@ dependencies {
|
||||
//磁盘缓存
|
||||
implementation 'com.jakewharton:disklrucache:2.0.2'
|
||||
//阿里云推送
|
||||
implementation 'com.aliyun.ams:alicloud-android-push:3.8.0'
|
||||
implementation 'com.aliyun.ams:alicloud-android-push:3.10.1'
|
||||
//百度地图
|
||||
implementation 'com.baidu.lbsyun:BaiduMapSDK_Location:9.7.0'
|
||||
//MMKV
|
||||
@@ -959,8 +961,6 @@ dependencies {
|
||||
implementation 'org.zeroturnaround:zt-zip:1.15'
|
||||
//更换字体框架
|
||||
implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
|
||||
//Java WebSocket
|
||||
implementation "org.java-websocket:Java-WebSocket:1.5.3"
|
||||
//状态栏透明
|
||||
implementation 'com.gitee.zackratos:UltimateBarX:0.8.0'
|
||||
// // 基础依赖包,必须要依赖
|
||||
|
||||
@@ -2,21 +2,17 @@ package com.aoleyun.sn.base;
|
||||
|
||||
import android.os.Build;
|
||||
import android.os.Process;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.multidex.MultiDexApplication;
|
||||
|
||||
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.aoleyun.sn.BuildConfig;
|
||||
import com.aoleyun.sn.manager.AllwinnerCubeMdmManager;
|
||||
import com.aoleyun.sn.manager.ConnectManager;
|
||||
import com.aoleyun.sn.manager.FileManager;
|
||||
import com.aoleyun.sn.manager.MapManager;
|
||||
import com.aoleyun.sn.network.NetInterfaceManager;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.aoleyun.sn.push.PushManager;
|
||||
import com.aoleyun.sn.rlog.LogDBManager;
|
||||
import com.aoleyun.sn.utils.JgyUtils;
|
||||
@@ -29,14 +25,6 @@ import com.hjq.toast.Toaster;
|
||||
import com.tencent.bugly.crashreport.CrashReport;
|
||||
import com.tencent.mmkv.MMKV;
|
||||
|
||||
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.core.Observer;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
|
||||
public class BaseApplication extends MultiDexApplication {
|
||||
private static final String TAG = "BaseApplication";
|
||||
|
||||
@@ -70,10 +58,8 @@ public class BaseApplication extends MultiDexApplication {
|
||||
xcrash.XCrash.init(this);
|
||||
|
||||
PushManager.init(this);
|
||||
initRegisterObservable();
|
||||
initAliasObservable();
|
||||
initTagObservable();
|
||||
aliyunPushInit();
|
||||
//阿里云推送统一由 AliyunPushManager 管理(初始化、注册、别名/标签、自动重试与状态检测)
|
||||
AliyunPushManager.init(this);
|
||||
NetInterfaceManager.init(this);
|
||||
if (JgyUtils.isAllWinnerDevice()) {
|
||||
AllwinnerCubeMdmManager.init(this);
|
||||
@@ -114,220 +100,4 @@ public class BaseApplication extends MultiDexApplication {
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
interface OnRegisterResult {
|
||||
void onResult(String code);
|
||||
}
|
||||
|
||||
private static OnRegisterResult mOnRegisterResult;
|
||||
|
||||
private void initRegisterObservable() {
|
||||
Log.e(TAG, "initTagObservable: ");
|
||||
Observable.create(new ObservableOnSubscribe<String>() {
|
||||
@Override
|
||||
public void subscribe(ObservableEmitter<String> emitter) {
|
||||
mOnRegisterResult = new OnRegisterResult() {
|
||||
@Override
|
||||
public void onResult(String code) {
|
||||
Log.e("initRegisterObservable", "onResult: " + code);
|
||||
emitter.onNext(code);
|
||||
}
|
||||
};
|
||||
}
|
||||
}).throttleLast(60, TimeUnit.SECONDS)
|
||||
.subscribe(new Observer<String>() {
|
||||
@Override
|
||||
public void onSubscribe(Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(String code) {
|
||||
Log.e("initRegisterObservable", "onNext: " + code);
|
||||
switch (code) {
|
||||
case "PUSH_20110":
|
||||
break;
|
||||
default:
|
||||
Log.e("initRegisterObservable", "onNext: 重新注册aliyunPush");
|
||||
aliyunPushInit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable e) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void aliyunPushInit() {
|
||||
// 特殊场景 需要定时拉起channel
|
||||
PushInitConfig config = new PushInitConfig.Builder()
|
||||
.application(this)
|
||||
.loopStartChannel(true)
|
||||
.loopInterval(60 * 10 * 1000)
|
||||
.build();
|
||||
PushServiceFactory.init(config);
|
||||
CloudPushService pushService = PushServiceFactory.getCloudPushService();
|
||||
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());
|
||||
setAlias();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMessage) {
|
||||
Log.e("AliyunPush", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
|
||||
mOnRegisterResult.onResult(errorCode);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
interface OnAliasResult {
|
||||
void onResult(String code);
|
||||
}
|
||||
|
||||
private static OnAliasResult mOnAliasResult;
|
||||
|
||||
private void initAliasObservable() {
|
||||
Log.e(TAG, "initAliasObservable: ");
|
||||
Observable.create(new ObservableOnSubscribe<String>() {
|
||||
@Override
|
||||
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
|
||||
mOnAliasResult = new OnAliasResult() {
|
||||
@Override
|
||||
public void onResult(String code) {
|
||||
Log.e("initAliasObservable", "onResult: " + code);
|
||||
emitter.onNext(code);
|
||||
}
|
||||
};
|
||||
}
|
||||
}).throttleLast(60, TimeUnit.SECONDS)
|
||||
.subscribe(new Observer<String>() {
|
||||
@Override
|
||||
public void onSubscribe(Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(String code) {
|
||||
Log.e("initAliasObservable", "onNext: " + code);
|
||||
switch (code) {
|
||||
case "PUSH_20101":
|
||||
aliyunPushInit();
|
||||
break;
|
||||
default:
|
||||
setAlias();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable e) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setAlias() {
|
||||
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
|
||||
String sn = Utils.getSerial(BaseApplication.this);
|
||||
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);
|
||||
mOnAliasResult.onResult(errorCode);
|
||||
}
|
||||
});
|
||||
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");
|
||||
mOnAliasResult.onResult(errorCode);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void onTagOperatorResult(String code) {
|
||||
onTagResult.onResult(code);
|
||||
}
|
||||
|
||||
private static OnTagResult onTagResult;
|
||||
|
||||
interface OnTagResult {
|
||||
void onResult(String code);
|
||||
}
|
||||
|
||||
private void initTagObservable() {
|
||||
Log.e(TAG, "initTagObservable: ");
|
||||
Observable.create(new ObservableOnSubscribe<String>() {
|
||||
@Override
|
||||
public void subscribe(ObservableEmitter<String> emitter) {
|
||||
onTagResult = new OnTagResult() {
|
||||
@Override
|
||||
public void onResult(String code) {
|
||||
Log.e("initTagObservable", "onResult: " + code);
|
||||
emitter.onNext(code);
|
||||
}
|
||||
};
|
||||
}
|
||||
}).throttleLast(60, TimeUnit.SECONDS)
|
||||
.subscribe(new Observer<String>() {
|
||||
@Override
|
||||
public void onSubscribe(Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(String code) {
|
||||
Log.e("initTagObservable", "onNext: " + code);
|
||||
switch (code) {
|
||||
case "PUSH_20101":
|
||||
aliyunPushInit();
|
||||
break;
|
||||
default:
|
||||
NetInterfaceManager.getInstance().getPushAndPubAppTag();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable e) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -19,12 +19,8 @@ import android.provider.Settings;
|
||||
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.aoleyun.sn.BuildConfig;
|
||||
import com.aoleyun.sn.activity.update.AppUpdateActivity;
|
||||
import com.aoleyun.sn.base.BaseApplication;
|
||||
import com.aoleyun.sn.bean.AdminAppInfo;
|
||||
import com.aoleyun.sn.bean.AppAttr;
|
||||
import com.aoleyun.sn.bean.AppDateInfo;
|
||||
@@ -84,6 +80,7 @@ import com.aoleyun.sn.network.api.aoleyun.UploadInfoApi;
|
||||
import com.aoleyun.sn.network.api.thirdparty.GetWhoisApi;
|
||||
import com.aoleyun.sn.network.cache.RxCacheManager;
|
||||
import com.aoleyun.sn.network.interceptor.RepeatRequestInterceptor;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.aoleyun.sn.rlog.LogDBManager;
|
||||
import com.aoleyun.sn.service.LogcatService;
|
||||
import com.aoleyun.sn.service.main.MainService;
|
||||
@@ -1325,9 +1322,9 @@ public class NetInterfaceManager {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (!BuildConfig.DEBUG) {
|
||||
// if (!BuildConfig.DEBUG) {
|
||||
ApkUtils.UninstallAPP(mContext, s);
|
||||
}
|
||||
// }
|
||||
Log.e("getDefaultDesktop", "UninstallAPP: " + s);
|
||||
}
|
||||
|
||||
@@ -2431,22 +2428,8 @@ public class NetInterfaceManager {
|
||||
public void clearAndAppendTags(Set<String> tagSets) {
|
||||
tagSets.add(JgyUtils.getInstance().getAppPlatform());
|
||||
Log.e(TAG, "clearAndAppendTags: " + tagSets);
|
||||
|
||||
String[] tag = new ArrayList<>(tagSets).toArray(new String[tagSets.size()]);
|
||||
CloudPushService pushService = PushServiceFactory.getCloudPushService();
|
||||
pushService.bindTag(CloudPushService.DEVICE_TARGET, tag, null, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String s) {
|
||||
Log.e("clearAndAppendTags", "bind tag " + Arrays.toString(tag) + " success\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMsg) {
|
||||
Log.e("clearAndAppendTags", "bind tag " + Arrays.toString(tag) + " failed." +
|
||||
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
|
||||
BaseApplication.onTagOperatorResult(errorCode);
|
||||
}
|
||||
});
|
||||
//标签绑定(含失败自动重试)统一由 AliyunPushManager 处理
|
||||
AliyunPushManager.getInstance().bindTags(tagSets);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
|
||||
@@ -0,0 +1,863 @@
|
||||
package com.aoleyun.sn.push;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
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.aoleyun.sn.utils.Utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 阿里云移动推送统一管理类。
|
||||
* <p>
|
||||
* 职责:
|
||||
* 1. 初始化 PushServiceFactory(含通道定时保活);
|
||||
* 2. 注册设备、绑定账号(别名)与标签;
|
||||
* 3. 失败自动重试(指数退避 + 时间窗内尝试次数熔断,熔断后由状态检测兜底);
|
||||
* 4. 定时 / 主动状态检测(checkChannelStatus),通道关闭时自动重新初始化并注册。
|
||||
* <p>
|
||||
* 并发约定(重要):
|
||||
* - {@link #mLock} 只保护状态位读写,任何持锁代码块内都禁止调用推送 SDK、读设备信息等可能阻塞的操作;
|
||||
* - SDK 初始化使用独立的 {@link #mInitLock},避免初始化耗时阻塞状态查询;
|
||||
* - 所有公共方法入口先用「快照 → 锁外执行」的方式决策,避免持锁期间等待 SDK 回调线程再次进锁而死等。
|
||||
* <p>
|
||||
* 所有推送 SDK 调用统一收口到本类,业务层不要再直接调用 PushServiceFactory.getCloudPushService()。
|
||||
*/
|
||||
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 STATUS_CHECK_MIN_GAP = 60 * 1000L;
|
||||
/**
|
||||
* 时间窗内允许发起的最大尝试次数,超过后只依赖定时状态检测自愈,避免重试风暴
|
||||
*/
|
||||
private static final int MAX_ATTEMPTS_PER_WINDOW = 12;
|
||||
/**
|
||||
* 尝试次数熔断窗口
|
||||
*/
|
||||
private static final long ATTEMPT_WINDOW = 10 * 60 * 1000L;
|
||||
/**
|
||||
* 重试间隔(指数退避),数组长度即单个任务的最大重试次数
|
||||
*/
|
||||
private static final long[] RETRY_DELAYS = {
|
||||
5 * 1000L,
|
||||
10 * 1000L,
|
||||
30 * 1000L,
|
||||
60 * 1000L,
|
||||
2 * 60 * 1000L,
|
||||
5 * 60 * 1000L
|
||||
};
|
||||
|
||||
/**
|
||||
* 前置流程决策结果:管理器未启动,需要先 start()
|
||||
*/
|
||||
private static final int NEXT_STOPPED = 0;
|
||||
/**
|
||||
* 目标状态已达成,无需动作
|
||||
*/
|
||||
private static final int NEXT_ALREADY = 1;
|
||||
/**
|
||||
* 同类任务正在执行,忽略本次请求
|
||||
*/
|
||||
private static final int NEXT_BUSY = 2;
|
||||
/**
|
||||
* 前置条件不满足,需要先执行前置流程
|
||||
*/
|
||||
private static final int NEXT_PREREQ = 3;
|
||||
/**
|
||||
* 状态位已置位,可以在锁外执行
|
||||
*/
|
||||
private static final int NEXT_PROCEED = 4;
|
||||
|
||||
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 mLock = new Object();
|
||||
/**
|
||||
* SDK 初始化锁:与状态锁分离
|
||||
*/
|
||||
private final Object mInitLock = new Object();
|
||||
|
||||
/**
|
||||
* 待绑定的标签,注册成功后自动补齐
|
||||
*/
|
||||
private final Set<String> mPendingTags = new LinkedHashSet<>();
|
||||
/**
|
||||
* 已成功绑定的标签,用于避免重复下发
|
||||
*/
|
||||
private final Set<String> mBoundTags = new LinkedHashSet<>();
|
||||
|
||||
private volatile CloudPushService mPushService;
|
||||
|
||||
private boolean mStarted;
|
||||
private boolean mRegistered;
|
||||
private boolean mRegistering;
|
||||
private boolean mBindingAlias;
|
||||
private boolean mAliasBound;
|
||||
private boolean mBindingTag;
|
||||
private int mRegisterRetryCount;
|
||||
private int mAliasRetryCount;
|
||||
private int mTagRetryCount;
|
||||
|
||||
/**
|
||||
* 熔断窗口起点(elapsedRealtime)
|
||||
*/
|
||||
private long mAttemptWindowStart;
|
||||
/**
|
||||
* 熔断窗口内已发起的尝试次数
|
||||
*/
|
||||
private int mAttemptCount;
|
||||
/**
|
||||
* 上次状态检测的时间(elapsedRealtime),用于去抖
|
||||
*/
|
||||
private long mLastStatusCheckUptime;
|
||||
|
||||
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() {
|
||||
if (!mStarted) {
|
||||
return;
|
||||
}
|
||||
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 (mLock) {
|
||||
if (mStarted) {
|
||||
return;
|
||||
}
|
||||
mStarted = true;
|
||||
resetAttemptBudgetLocked();
|
||||
}
|
||||
Log.d(TAG, "start: begin");
|
||||
initSdk(false);
|
||||
register();
|
||||
mHandler.removeCallbacks(mStatusCheckTask);
|
||||
mHandler.postDelayed(mStatusCheckTask, STATUS_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止本类的所有定时任务并复位状态,之后再次 {@link #start()} 会完整重走初始化与注册流程。
|
||||
* <p>
|
||||
* 注意:这里只停本地调度,SDK 通道本身不受影响(本应用为常驻保活场景,不主动关闭通道)。
|
||||
*/
|
||||
public void release() {
|
||||
synchronized (mLock) {
|
||||
mStarted = false;
|
||||
mRegistered = false;
|
||||
mRegistering = false;
|
||||
mBindingAlias = false;
|
||||
mAliasBound = false;
|
||||
mBindingTag = false;
|
||||
mRegisterRetryCount = 0;
|
||||
mAliasRetryCount = 0;
|
||||
mTagRetryCount = 0;
|
||||
mBoundTags.clear();
|
||||
resetAttemptBudgetLocked();
|
||||
mLastStatusCheckUptime = 0;
|
||||
}
|
||||
mHandler.removeCallbacks(mRegisterTask);
|
||||
mHandler.removeCallbacks(mAliasTask);
|
||||
mHandler.removeCallbacks(mTagTask);
|
||||
mHandler.removeCallbacks(mStatusCheckTask);
|
||||
synchronized (mInitLock) {
|
||||
// 置空后下次 start 会重新初始化 SDK,避免复用已失效的实例
|
||||
mPushService = null;
|
||||
}
|
||||
Log.d(TAG, "release: all tasks cancelled");
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 SDK。
|
||||
*
|
||||
* @param force true 表示强制重新初始化(通道关闭后需要重走 init)
|
||||
* @return 是否初始化成功
|
||||
*/
|
||||
private boolean initSdk(boolean force) {
|
||||
if (mApplication == null) {
|
||||
Log.e(TAG, "initSdk: application is null");
|
||||
return false;
|
||||
}
|
||||
synchronized (mInitLock) {
|
||||
if (!force && mPushService != null) {
|
||||
return true;
|
||||
}
|
||||
CloudPushService service = null;
|
||||
try {
|
||||
// 特殊场景 需要定时拉起 channel
|
||||
PushInitConfig config = new PushInitConfig.Builder()
|
||||
.application(mApplication)
|
||||
.loopStartChannel(true)
|
||||
.loopInterval(LOOP_CHANNEL_INTERVAL)
|
||||
.build();
|
||||
PushServiceFactory.init(config);
|
||||
service = PushServiceFactory.getCloudPushService();
|
||||
if (service != null) {
|
||||
service.setLogLevel(CloudPushService.LOG_DEBUG);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "initSdk: failed " + e.getMessage());
|
||||
}
|
||||
mPushService = service;
|
||||
if (service == null) {
|
||||
Log.e(TAG, "initSdk: push service is null");
|
||||
return false;
|
||||
}
|
||||
Log.d(TAG, "initSdk: success");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取可用的推送服务实例,必要时初始化
|
||||
*/
|
||||
private CloudPushService obtainService() {
|
||||
CloudPushService service = mPushService;
|
||||
if (service != null) {
|
||||
return service;
|
||||
}
|
||||
initSdk(false);
|
||||
return mPushService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册设备(幂等,失败自动重试)
|
||||
*/
|
||||
public void register() {
|
||||
final int next;
|
||||
synchronized (mLock) {
|
||||
if (!mStarted) {
|
||||
next = NEXT_STOPPED;
|
||||
} else if (mRegistered) {
|
||||
next = NEXT_ALREADY;
|
||||
} else if (mRegistering) {
|
||||
next = NEXT_BUSY;
|
||||
} else {
|
||||
mRegistering = true;
|
||||
next = NEXT_PROCEED;
|
||||
}
|
||||
}
|
||||
switch (next) {
|
||||
case NEXT_STOPPED:
|
||||
Log.d(TAG, "register: 管理器未启动,先执行 start");
|
||||
start();
|
||||
return;
|
||||
case NEXT_ALREADY:
|
||||
bindAlias();
|
||||
flushTags();
|
||||
return;
|
||||
case NEXT_BUSY:
|
||||
Log.d(TAG, "register: 注册进行中,忽略重复请求");
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!takeAttemptBudget("register")) {
|
||||
finishRegistering();
|
||||
return;
|
||||
}
|
||||
CloudPushService service = obtainService();
|
||||
if (service == null) {
|
||||
finishRegistering();
|
||||
scheduleRetry(mRegisterTask, nextRegisterRetry(), "register");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
service.register(mContext, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String response) {
|
||||
boolean started;
|
||||
synchronized (mLock) {
|
||||
mRegistering = false;
|
||||
started = mStarted;
|
||||
if (started) {
|
||||
mRegistered = true;
|
||||
mRegisterRetryCount = 0;
|
||||
}
|
||||
}
|
||||
if (!started) {
|
||||
Log.d(TAG, "register success 但管理器已停止,忽略");
|
||||
return;
|
||||
}
|
||||
Log.d(TAG, "register success, deviceId: " + getDeviceId());
|
||||
bindAlias();
|
||||
flushTags();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMessage) {
|
||||
if (CODE_ALREADY_REGISTERED.equals(errorCode)) {
|
||||
synchronized (mLock) {
|
||||
mRegistering = false;
|
||||
mRegistered = true;
|
||||
mRegisterRetryCount = 0;
|
||||
}
|
||||
Log.d(TAG, "register: 设备已注册,继续绑定别名与标签");
|
||||
bindAlias();
|
||||
flushTags();
|
||||
return;
|
||||
}
|
||||
Log.w(TAG, "register failed, errorCode: " + errorCode + ", errorMessage: " + errorMessage);
|
||||
synchronized (mLock) {
|
||||
mRegistering = false;
|
||||
mRegistered = false;
|
||||
}
|
||||
scheduleRetry(mRegisterTask, nextRegisterRetry(), "register");
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "register: exception " + e.getMessage());
|
||||
finishRegistering();
|
||||
scheduleRetry(mRegisterTask, nextRegisterRetry(), "register");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定账号与别名(设备序列号 SN),失败自动重试
|
||||
*/
|
||||
public void bindAlias() {
|
||||
final int next;
|
||||
synchronized (mLock) {
|
||||
if (!mStarted) {
|
||||
next = NEXT_STOPPED;
|
||||
} else if (!mRegistered) {
|
||||
next = NEXT_PREREQ;
|
||||
} else if (mAliasBound) {
|
||||
next = NEXT_ALREADY;
|
||||
} else if (mBindingAlias) {
|
||||
next = NEXT_BUSY;
|
||||
} else {
|
||||
mBindingAlias = true;
|
||||
next = NEXT_PROCEED;
|
||||
}
|
||||
}
|
||||
switch (next) {
|
||||
case NEXT_STOPPED:
|
||||
Log.d(TAG, "bindAlias: 管理器未启动,先执行 start");
|
||||
start();
|
||||
return;
|
||||
case NEXT_PREREQ:
|
||||
Log.d(TAG, "bindAlias: 设备未注册,先注册");
|
||||
register();
|
||||
return;
|
||||
case NEXT_ALREADY:
|
||||
return;
|
||||
case NEXT_BUSY:
|
||||
Log.d(TAG, "bindAlias: 正在绑定中,忽略重复请求");
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// 锁外读取设备序列号,避免属性 / IO 读取阻塞状态锁
|
||||
final String sn = Utils.getSerial(mContext);
|
||||
if (TextUtils.isEmpty(sn)) {
|
||||
Log.w(TAG, "bindAlias: sn 为空,稍后重试");
|
||||
finishAlias(false);
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "bindAlias");
|
||||
return;
|
||||
}
|
||||
if (!takeAttemptBudget("bindAlias")) {
|
||||
finishAlias(false);
|
||||
return;
|
||||
}
|
||||
CloudPushService service = obtainService();
|
||||
if (service == null) {
|
||||
finishAlias(false);
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "bindAlias");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
service.bindAccount(sn, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String s) {
|
||||
Log.d(TAG, "bind account " + sn + " success");
|
||||
addAlias(sn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMsg) {
|
||||
Log.w(TAG, "bind account " + sn + " failed, errorCode: " + errorCode
|
||||
+ ", errorMsg: " + errorMsg);
|
||||
onAliasFailed(errorCode);
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "bindAlias: exception " + e.getMessage());
|
||||
finishAlias(false);
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "bindAlias");
|
||||
}
|
||||
}
|
||||
|
||||
private void addAlias(final String sn) {
|
||||
CloudPushService service = obtainService();
|
||||
if (service == null) {
|
||||
finishAlias(false);
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "addAlias");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
service.addAlias(sn, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String s) {
|
||||
finishAlias(true);
|
||||
Log.d(TAG, "add alias " + sn + " success");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMsg) {
|
||||
Log.w(TAG, "add alias " + sn + " failed, errorCode: " + errorCode
|
||||
+ ", errorMsg: " + errorMsg);
|
||||
onAliasFailed(errorCode);
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "addAlias: exception " + e.getMessage());
|
||||
finishAlias(false);
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "addAlias");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 别名绑定失败统一处理:未注册错误码直接重新注册,其它错误退避重试
|
||||
*/
|
||||
private void onAliasFailed(String errorCode) {
|
||||
boolean reRegister = CODE_NOT_REGISTERED.equals(errorCode);
|
||||
synchronized (mLock) {
|
||||
mBindingAlias = false;
|
||||
mAliasBound = false;
|
||||
if (reRegister) {
|
||||
mRegistered = false;
|
||||
mRegisterRetryCount = 0;
|
||||
}
|
||||
}
|
||||
if (reRegister) {
|
||||
Log.w(TAG, "别名绑定失败(" + CODE_NOT_REGISTERED + "),重新注册设备");
|
||||
register();
|
||||
return;
|
||||
}
|
||||
scheduleRetry(mAliasTask, nextAliasRetry(), "bindAlias");
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定标签,失败自动重试;设备未注册时先注册,注册成功后自动补齐。
|
||||
* 传入的标签集合与已成功绑定的集合一致时直接忽略。
|
||||
*/
|
||||
public void bindTags(Set<String> tagSets) {
|
||||
if (tagSets == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (mLock) {
|
||||
if (mBoundTags.equals(tagSets)) {
|
||||
Log.d(TAG, "bindTags: 标签未变化,忽略 " + tagSets);
|
||||
return;
|
||||
}
|
||||
mPendingTags.clear();
|
||||
mPendingTags.addAll(tagSets);
|
||||
}
|
||||
doBindTags();
|
||||
}
|
||||
|
||||
private void flushTags() {
|
||||
boolean hasPending;
|
||||
synchronized (mLock) {
|
||||
hasPending = !mPendingTags.isEmpty();
|
||||
}
|
||||
if (hasPending) {
|
||||
doBindTags();
|
||||
}
|
||||
}
|
||||
|
||||
private void doBindTags() {
|
||||
final int next;
|
||||
String[] tags = null;
|
||||
synchronized (mLock) {
|
||||
if (!mStarted) {
|
||||
next = NEXT_STOPPED;
|
||||
} else if (mPendingTags.isEmpty() || isTagsBoundLocked()) {
|
||||
next = NEXT_ALREADY;
|
||||
} else if (!mRegistered) {
|
||||
next = NEXT_PREREQ;
|
||||
} else if (mBindingTag) {
|
||||
next = NEXT_BUSY;
|
||||
} else {
|
||||
mBindingTag = true;
|
||||
tags = mPendingTags.toArray(new String[0]);
|
||||
next = NEXT_PROCEED;
|
||||
}
|
||||
}
|
||||
switch (next) {
|
||||
case NEXT_STOPPED:
|
||||
Log.d(TAG, "doBindTags: 管理器未启动,先执行 start");
|
||||
start();
|
||||
return;
|
||||
case NEXT_ALREADY:
|
||||
return;
|
||||
case NEXT_PREREQ:
|
||||
Log.d(TAG, "doBindTags: 设备未注册,先注册");
|
||||
register();
|
||||
return;
|
||||
case NEXT_BUSY:
|
||||
Log.d(TAG, "doBindTags: 正在绑定中,忽略重复请求");
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!takeAttemptBudget("bindTag")) {
|
||||
finishTag(null);
|
||||
return;
|
||||
}
|
||||
CloudPushService service = obtainService();
|
||||
if (service == null) {
|
||||
finishTag(null);
|
||||
scheduleRetry(mTagTask, nextTagRetry(), "bindTag");
|
||||
return;
|
||||
}
|
||||
final String[] finalTags = tags;
|
||||
try {
|
||||
service.bindTag(CloudPushService.DEVICE_TARGET, finalTags, null, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String s) {
|
||||
finishTag(finalTags);
|
||||
Log.d(TAG, "bind tag success: " + Arrays.toString(finalTags));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMsg) {
|
||||
Log.w(TAG, "bind tag failed: " + Arrays.toString(finalTags)
|
||||
+ ", errorCode: " + errorCode + ", errorMsg: " + errorMsg);
|
||||
boolean reRegister = CODE_NOT_REGISTERED.equals(errorCode);
|
||||
synchronized (mLock) {
|
||||
mBindingTag = false;
|
||||
mBoundTags.clear();
|
||||
if (reRegister) {
|
||||
mRegistered = false;
|
||||
mRegisterRetryCount = 0;
|
||||
}
|
||||
}
|
||||
if (reRegister) {
|
||||
register();
|
||||
return;
|
||||
}
|
||||
scheduleRetry(mTagTask, nextTagRetry(), "bindTag");
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "doBindTags: exception " + e.getMessage());
|
||||
finishTag(null);
|
||||
scheduleRetry(mTagTask, nextTagRetry(), "bindTag");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测推送通道状态,通道关闭或未注册时自动重新初始化并注册。
|
||||
* 可用于开机、亮屏、网络恢复等时机主动调用(内部按 {@link #STATUS_CHECK_MIN_GAP} 去抖)。
|
||||
*/
|
||||
public void checkChannelStatus() {
|
||||
if (!mStarted) {
|
||||
Log.d(TAG, "checkChannelStatus: 管理器未启动,先执行 start");
|
||||
start();
|
||||
return;
|
||||
}
|
||||
synchronized (mLock) {
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (mLastStatusCheckUptime != 0 && now - mLastStatusCheckUptime < STATUS_CHECK_MIN_GAP) {
|
||||
Log.d(TAG, "checkChannelStatus: 距上次检测不足 "
|
||||
+ (STATUS_CHECK_MIN_GAP / 1000) + "s,忽略本次请求");
|
||||
return;
|
||||
}
|
||||
mLastStatusCheckUptime = now;
|
||||
}
|
||||
if (!takeAttemptBudget("checkChannelStatus")) {
|
||||
return;
|
||||
}
|
||||
CloudPushService service = obtainService();
|
||||
if (service == null) {
|
||||
Log.w(TAG, "checkChannelStatus: push service 为空,直接走注册流程");
|
||||
register();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
service.checkPushChannelStatus(new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String response) {
|
||||
if ("on".equals(response)) {
|
||||
Log.d(TAG, "checkPushChannelStatus onSuccess: " + response);
|
||||
//通道正常,自愈注册 / 别名 / 标签
|
||||
selfHeal();
|
||||
return;
|
||||
}
|
||||
//通道关闭,重新初始化并注册
|
||||
Log.w(TAG, "推送通道已关闭,重新初始化并注册");
|
||||
synchronized (mLock) {
|
||||
mRegistered = false;
|
||||
mAliasBound = false;
|
||||
mRegisterRetryCount = 0;
|
||||
mAliasRetryCount = 0;
|
||||
mBoundTags.clear();
|
||||
// 通道关闭是权威信号,重置熔断窗口,给新周期一次完整重试机会
|
||||
resetAttemptBudgetLocked();
|
||||
}
|
||||
initSdk(true);
|
||||
register();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMessage) {
|
||||
Log.w(TAG, "checkPushChannelStatus onFailed, errorCode: " + errorCode
|
||||
+ ", errorMessage: " + errorMessage);
|
||||
selfHeal();
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
Log.e(TAG, "checkChannelStatus: exception " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通道正常时补齐未完成的注册 / 别名 / 标签
|
||||
*/
|
||||
private void selfHeal() {
|
||||
final boolean needRegister;
|
||||
final boolean needAlias;
|
||||
final boolean needTags;
|
||||
synchronized (mLock) {
|
||||
needRegister = !mRegistered;
|
||||
needAlias = mRegistered && !mAliasBound;
|
||||
needTags = mRegistered && !mPendingTags.isEmpty() && !mBindingTag;
|
||||
}
|
||||
if (needRegister) {
|
||||
Log.d(TAG, "自愈: 设备未注册,重新注册");
|
||||
register();
|
||||
return;
|
||||
}
|
||||
if (needAlias) {
|
||||
Log.d(TAG, "自愈: 别名未绑定");
|
||||
bindAlias();
|
||||
}
|
||||
if (needTags) {
|
||||
Log.d(TAG, "自愈: 标签未绑定");
|
||||
doBindTags();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 设备是否已注册成功
|
||||
*/
|
||||
public boolean isRegistered() {
|
||||
synchronized (mLock) {
|
||||
return mRegistered;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 待绑定标签是否与已成功绑定的标签一致(需在 mLock 内调用)
|
||||
*/
|
||||
private boolean isTagsBoundLocked() {
|
||||
return !mBoundTags.isEmpty() && mBoundTags.equals(mPendingTags);
|
||||
}
|
||||
|
||||
private void finishRegistering() {
|
||||
synchronized (mLock) {
|
||||
mRegistering = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束别名绑定流程
|
||||
*
|
||||
* @param success true 表示绑定成功
|
||||
*/
|
||||
private void finishAlias(boolean success) {
|
||||
synchronized (mLock) {
|
||||
mBindingAlias = false;
|
||||
mAliasBound = success;
|
||||
if (success) {
|
||||
mAliasRetryCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束标签绑定流程
|
||||
*
|
||||
* @param boundTags 绑定成功时传实际绑定的标签,失败传 null
|
||||
*/
|
||||
private void finishTag(String[] boundTags) {
|
||||
synchronized (mLock) {
|
||||
mBindingTag = false;
|
||||
if (boundTags == null) {
|
||||
return;
|
||||
}
|
||||
mTagRetryCount = 0;
|
||||
mBoundTags.clear();
|
||||
mBoundTags.addAll(Arrays.asList(boundTags));
|
||||
}
|
||||
}
|
||||
|
||||
private int nextRegisterRetry() {
|
||||
synchronized (mLock) {
|
||||
return mRegisterRetryCount++;
|
||||
}
|
||||
}
|
||||
|
||||
private int nextAliasRetry() {
|
||||
synchronized (mLock) {
|
||||
return mAliasRetryCount++;
|
||||
}
|
||||
}
|
||||
|
||||
private int nextTagRetry() {
|
||||
synchronized (mLock) {
|
||||
return mTagRetryCount++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试次数熔断:同一时间窗内发起尝试过多时直接放弃本次,等待定时状态检测兜底,
|
||||
* 避免通道异常时被外部轮询(亮屏 / 网络变化)反复放大成重试风暴。
|
||||
*
|
||||
* @param action 任务名,仅用于日志
|
||||
* @return true 表示允许发起本次尝试
|
||||
*/
|
||||
private boolean takeAttemptBudget(String action) {
|
||||
synchronized (mLock) {
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (mAttemptWindowStart == 0 || now - mAttemptWindowStart > ATTEMPT_WINDOW) {
|
||||
mAttemptWindowStart = now;
|
||||
mAttemptCount = 0;
|
||||
}
|
||||
if (mAttemptCount >= MAX_ATTEMPTS_PER_WINDOW) {
|
||||
Log.w(TAG, action + " 在 " + (ATTEMPT_WINDOW / 60000L) + " 分钟内已尝试 "
|
||||
+ MAX_ATTEMPTS_PER_WINDOW + " 次,暂停重试,等待定时状态检测自愈");
|
||||
return false;
|
||||
}
|
||||
mAttemptCount++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAttemptBudgetLocked() {
|
||||
mAttemptWindowStart = SystemClock.elapsedRealtime();
|
||||
mAttemptCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指数退避重试
|
||||
*
|
||||
* @param task 重试任务
|
||||
* @param attempt 当前已重试次数
|
||||
* @param action 任务名,仅用于日志
|
||||
*/
|
||||
private void scheduleRetry(Runnable task, int attempt, String action) {
|
||||
if (attempt >= RETRY_DELAYS.length) {
|
||||
Log.e(TAG, action + " 重试次数已达上限(" + RETRY_DELAYS.length + "),等待下次状态检测自愈");
|
||||
return;
|
||||
}
|
||||
long delay = RETRY_DELAYS[attempt];
|
||||
Log.d(TAG, action + " 失败,将在 " + delay + "ms 后进行第 " + (attempt + 1) + " 次重试");
|
||||
mHandler.removeCallbacks(task);
|
||||
mHandler.postDelayed(task, delay);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.aoleyun.sn.service;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
import org.java_websocket.drafts.Draft_6455;
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
public class JWebSocketClient extends WebSocketClient {
|
||||
public JWebSocketClient(URI serverUri) {
|
||||
super(serverUri, new Draft_6455());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(ServerHandshake handshakedata) {
|
||||
Log.e("JWebSocketClient", "onOpen()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
Log.e("JWebSocketClient", "onMessage()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
Log.e("JWebSocketClient", "onClose():" + reason);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception ex) {
|
||||
Log.e("JWebSocketClient", "onError():" + ex.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -26,10 +26,13 @@ import com.aoleyun.sn.utils.Utils;
|
||||
import com.blankj.utilcode.util.NetworkUtils;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.WebSocket;
|
||||
import okhttp3.WebSocketListener;
|
||||
|
||||
/**
|
||||
* 主进程 双进程通讯
|
||||
@@ -40,15 +43,71 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
|
||||
private final static String TAG = "StepService";
|
||||
|
||||
public volatile JWebSocketClient client;
|
||||
// ---------------------------- 时间/策略常量 ----------------------------
|
||||
/**
|
||||
* 心跳与健康检查间隔
|
||||
*/
|
||||
private static final long HEART_BEAT_RATE = 30 * 1000;
|
||||
/**
|
||||
* 消息最小发送间隔(防抖)
|
||||
*/
|
||||
private static final long MIN_MESSAGE_INTERVAL = 15 * 1000;
|
||||
/**
|
||||
* 握手超时:服务器迟迟不回 101 时主动放弃,避免连接永久挂起
|
||||
*/
|
||||
private static final long HANDSHAKE_TIMEOUT = 20 * 1000;
|
||||
/**
|
||||
* 重连退避上限
|
||||
*/
|
||||
private static final long MAX_RETRY_DELAY = 5 * 60 * 1000;
|
||||
/**
|
||||
* OkHttp 心跳 ping 间隔(秒),用于发现半死连接
|
||||
*/
|
||||
private static final int PING_INTERVAL = 30;
|
||||
|
||||
/**
|
||||
* WebSocket 长连接专用 OkHttpClient:独立实例,避免被业务请求的拦截器(token、日志等)影响。
|
||||
*/
|
||||
private static final OkHttpClient WS_CLIENT = new OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
// 长连接不能靠读超时判断存活,置 0 关闭
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.writeTimeout(15, TimeUnit.SECONDS)
|
||||
// 主动 ping:pong 超时(半死连接/NAT 超时)时 OkHttp 会 cancel 并回调 onFailure
|
||||
.pingInterval(PING_INTERVAL, TimeUnit.SECONDS)
|
||||
.retryOnConnectionFailure(true)
|
||||
.build();
|
||||
|
||||
/**
|
||||
* 当前连接
|
||||
*/
|
||||
private volatile WebSocket webSocket;
|
||||
/**
|
||||
* 当前长连接是否可用(已收到 onOpen)
|
||||
*/
|
||||
private volatile boolean wsOpen;
|
||||
/**
|
||||
* 当前连接标识,用于丢弃已过期连接的回调
|
||||
*/
|
||||
private volatile Object wsToken;
|
||||
/**
|
||||
* 握手占位:区分“正在握手”和“没有连接”,保证同一时刻只有一条在途连接
|
||||
*/
|
||||
private volatile boolean attempting;
|
||||
/**
|
||||
* 建连互斥锁
|
||||
*/
|
||||
private final Object wsLock = new Object();
|
||||
/**
|
||||
* 下次重连的退避间隔,连接成功后复位
|
||||
*/
|
||||
private volatile long retryDelay = HEART_BEAT_RATE;
|
||||
|
||||
private volatile boolean destroyed;
|
||||
private volatile boolean connectionEnabled = true;
|
||||
private volatile boolean connectionEnabled;
|
||||
private boolean guardBound;
|
||||
private final AtomicBoolean connecting = new AtomicBoolean();
|
||||
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
|
||||
private final JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
|
||||
|
||||
// 新增防抖控制变量
|
||||
private static final long MIN_MESSAGE_INTERVAL = 15 * 1000; // 15秒最小消息间隔
|
||||
private volatile long lastMessageTime = 0;
|
||||
private final Object sendLock = new Object();
|
||||
|
||||
@@ -59,7 +118,10 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
|
||||
@Override
|
||||
public void onConnected(NetworkUtils.NetworkType networkType) {
|
||||
// connect();
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
// 网络恢复:清空退避,立即重新检查一次连接
|
||||
retryDelay = HEART_BEAT_RATE;
|
||||
mHandler.post(heartBeatRunnable);
|
||||
}
|
||||
|
||||
//用于Activity和service通讯
|
||||
@@ -72,7 +134,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
private ServiceConnection mServiceConnection = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
|
||||
Log.w(TAG, "StepService:建立链接");
|
||||
Log.w(TAG, "onServiceConnected: StepService:建立链接");
|
||||
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(StepService.this, GuardService.class.getName());
|
||||
if (!isServiceRunning) {
|
||||
Intent i = new Intent(StepService.this, GuardService.class);
|
||||
@@ -99,8 +161,12 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
Log.d(TAG, "onCreate: ");
|
||||
|
||||
NetworkUtils.registerNetworkStatusChangedListener(this);
|
||||
registerScreenLockReceiver();
|
||||
// 息屏状态下被拉起(START_STICKY / 守护进程拉起)时不建连,等亮屏广播恢复
|
||||
connectionEnabled = JgyUtils.getInstance().isScreenOn();
|
||||
//初始化websocket
|
||||
initSocketClient();
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
|
||||
@@ -110,7 +176,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
// startForeground(1, new Notification());
|
||||
// 绑定建立链接
|
||||
Log.e("JWebSocketClientService", "onStartCommand: ");
|
||||
Log.d(TAG, "onStartCommand: ");
|
||||
if (!guardBound) {
|
||||
guardBound = bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||||
}
|
||||
@@ -141,9 +207,9 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
Log.e(TAG, "onReceive:" + action);
|
||||
Log.e(TAG, "ScreenLockReceiver onReceive:" + action);
|
||||
if (TextUtils.isEmpty(action)) {
|
||||
Log.e(TAG, "onReceive: is NULL");
|
||||
Log.e(TAG, "ScreenLockReceiver onReceive: is NULL");
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
@@ -151,6 +217,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
case Intent.ACTION_USER_PRESENT:
|
||||
case Intent.ACTION_SCREEN_ON:
|
||||
connectionEnabled = true;
|
||||
retryDelay = HEART_BEAT_RATE; // 亮屏后立即重试,不复用退避间隔
|
||||
mHandler.removeCallbacks(heartBeatRunnable);
|
||||
mHandler.post(heartBeatRunnable);//开启心跳检测
|
||||
sendMsg();
|
||||
@@ -191,78 +258,144 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
* 初始化websocket连接
|
||||
*/
|
||||
private void initSocketClient() {
|
||||
if (destroyed || !connectionEnabled || connecting.get()) return;
|
||||
URI uri = URI.create(BuildConfig.WEBSOCKET_URL + "device?sn=" + Utils.getSerial(StepService.this));
|
||||
client = new JWebSocketClient(uri) {
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
Log.i("JWebSocketClientService", "收到服务器发来的消息:" + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(ServerHandshake handshakedata) {
|
||||
super.onOpen(handshakedata);
|
||||
Log.i("JWebSocketClientService", "websocket连接成功");
|
||||
mHandler.post(() -> {
|
||||
if (!destroyed && connectionEnabled && client == this) {
|
||||
lastMessageTime = 0;
|
||||
sendMsg();
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
super.onClose(code, reason, remote);
|
||||
Log.i("JWebSocketClientService", "websocket连接关闭");
|
||||
// client.close();
|
||||
// initSocketClient();
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception ex) {
|
||||
super.onError(ex);
|
||||
Log.i("JWebSocketClientService", "websocket连接错误:" + ex.getMessage());
|
||||
// client.close();
|
||||
// initSocketClient();
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "postDelayed off");
|
||||
}
|
||||
}
|
||||
};
|
||||
connect();
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
connectSocket();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接websocket
|
||||
* 建连入口:同一时刻最多一条在途连接,失败按退避间隔重试,息屏/无网不建连
|
||||
*/
|
||||
private void connect() {
|
||||
connectSocket(false);
|
||||
private void connectSocket() {
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
if (!JgyUtils.getInstance().isScreenOn()) {
|
||||
Log.i(TAG, "screen off, skip connect");
|
||||
return;
|
||||
}
|
||||
if (!NetworkUtils.isConnected()) {
|
||||
Log.i(TAG, "network unavailable, retry later");
|
||||
scheduleRetry();
|
||||
return;
|
||||
}
|
||||
synchronized (wsLock) {
|
||||
if (attempting || wsOpen) {
|
||||
// 已有在途连接或已连接,保持心跳链即可,不重复建连
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
return;
|
||||
}
|
||||
attempting = true;
|
||||
}
|
||||
final Object token = new Object();
|
||||
wsToken = token;
|
||||
new Thread(() -> doConnect(token), "device-websocket-connect").start();
|
||||
}
|
||||
|
||||
private void connectSocket(boolean reconnect) {
|
||||
final JWebSocketClient socket = client;
|
||||
if (destroyed || !connectionEnabled || socket == null || !connecting.compareAndSet(false, true))
|
||||
private void doConnect(Object token) {
|
||||
WebSocket pending;
|
||||
try {
|
||||
Request request = new Request.Builder()
|
||||
.url(BuildConfig.WEBSOCKET_URL + "device?sn=" + Utils.getSerial(StepService.this))
|
||||
.build();
|
||||
pending = WS_CLIENT.newWebSocket(request, new WsListener(token));
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "WebSocket connection failed", e);
|
||||
if (token == wsToken) attempting = false;
|
||||
scheduleRetry();
|
||||
return;
|
||||
new Thread(() -> {
|
||||
try {
|
||||
if (destroyed || !connectionEnabled || socket != client) return;
|
||||
if (reconnect) socket.reconnectBlocking();
|
||||
else socket.connectBlocking();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "WebSocket connection failed", e);
|
||||
} finally {
|
||||
connecting.set(false);
|
||||
if (destroyed || !connectionEnabled || socket != client) socket.close();
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
}
|
||||
if (destroyed || !connectionEnabled || token != wsToken) {
|
||||
// 建连过程中已息屏/销毁/被新连接取代,直接丢弃
|
||||
pending.cancel();
|
||||
return;
|
||||
}
|
||||
// 握手超时兜底:服务器不回 101 时主动 cancel,触发 onFailure 走统一断开流程
|
||||
mHandler.postDelayed(() -> {
|
||||
if (token == wsToken && attempting && !wsOpen) {
|
||||
Log.w(TAG, "websocket handshake timeout, cancel");
|
||||
pending.cancel();
|
||||
}
|
||||
}, "device-websocket-connect").start();
|
||||
}, HANDSHAKE_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* OkHttp WebSocket 回调,全部在 OkHttp 内部线程上执行
|
||||
*/
|
||||
private class WsListener extends WebSocketListener {
|
||||
private final Object token;
|
||||
|
||||
WsListener(Object token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(WebSocket ws, Response response) {
|
||||
if (destroyed || !connectionEnabled || token != wsToken) {
|
||||
// 已息屏/已销毁/已被新连接取代,直接丢弃这条连接
|
||||
ws.cancel();
|
||||
return;
|
||||
}
|
||||
attempting = false;
|
||||
retryDelay = HEART_BEAT_RATE; // 连接成功后复位退避
|
||||
webSocket = ws;
|
||||
wsOpen = true;
|
||||
Log.i(TAG, "onOpen: websocket连接成功");
|
||||
mHandler.post(() -> {
|
||||
if (!destroyed && connectionEnabled && token == wsToken) {
|
||||
lastMessageTime = 0;
|
||||
sendMsg();
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket ws, String text) {
|
||||
Log.i(TAG, "onMessage: 收到服务器发来的消息:" + text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosing(WebSocket ws, int code, String reason) {
|
||||
// 服务端发起关闭,本地完成关闭流程
|
||||
ws.close(1000, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosed(WebSocket ws, int code, String reason) {
|
||||
Log.i(TAG, "onClosed: websocket连接关闭");
|
||||
handleDisconnected(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(WebSocket ws, Throwable t, Response response) {
|
||||
Log.i(TAG, "onFailure: websocket连接错误:" + (t == null ? "unknown" : t.getMessage()));
|
||||
handleDisconnected(token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接断开后的统一处理,息屏时不重连
|
||||
*/
|
||||
private void handleDisconnected(Object token) {
|
||||
if (token != wsToken) return; // 过期连接的回调,忽略
|
||||
attempting = false;
|
||||
wsOpen = false;
|
||||
webSocket = null;
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
scheduleRetry();//按退避间隔重连
|
||||
} else {
|
||||
Log.i(TAG, "handleDisconnected: postDelayed off");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按退避间隔安排下一次重连:间隔逐次翻倍,上限 MAX_RETRY_DELAY,连接成功后复位
|
||||
*/
|
||||
private void scheduleRetry() {
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
long delay = retryDelay;
|
||||
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY);
|
||||
Log.i(TAG, "scheduleRetry: websocket " + delay + "ms 后重连");
|
||||
scheduleHeartbeat(delay);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,11 +406,12 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
long currentTime = SystemClock.elapsedRealtime();
|
||||
// 检查时间间隔和连接状态
|
||||
if (lastMessageTime != 0 && currentTime - lastMessageTime < MIN_MESSAGE_INTERVAL) {
|
||||
Log.w("JWebSocketClientService", "消息发送过于频繁,已忽略");
|
||||
Log.w(TAG, "sendMsg: 消息发送过于频繁,已忽略");
|
||||
return;
|
||||
}
|
||||
if (client == null || !client.isOpen()) {
|
||||
Log.w("JWebSocketClientService", "连接未建立,取消发送");
|
||||
WebSocket socket = webSocket;
|
||||
if (socket == null || !wsOpen) {
|
||||
Log.w(TAG, "sendMsg: 连接未建立,取消发送");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -285,9 +419,14 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
jsonObject.addProperty("type", "ping");
|
||||
jsonObject.addProperty("sn", Utils.getSerial(this));
|
||||
|
||||
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
|
||||
Log.i(TAG, "sendMsg: 发送的消息:" + jsonObject.toString());
|
||||
try {
|
||||
client.send(jsonObject.toString());
|
||||
if (!socket.send(jsonObject.toString())) {
|
||||
// 入队失败说明连接已关闭/正在关闭,判定为异常,交给 onFailure 走重连
|
||||
Log.w(TAG, "sendMsg: 消息入队失败,判定连接异常");
|
||||
socket.cancel();
|
||||
return;
|
||||
}
|
||||
lastMessageTime = currentTime; // 更新最后发送时间
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "sendMsg: " + e.getMessage());
|
||||
@@ -300,19 +439,21 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
* 断开连接
|
||||
*/
|
||||
private void closeConnect() {
|
||||
try {
|
||||
if (null != client) {
|
||||
client.close();
|
||||
attempting = false;
|
||||
wsOpen = false;
|
||||
wsToken = new Object(); // 使在途回调失效,避免断开后又被重连
|
||||
WebSocket socket = webSocket;
|
||||
webSocket = null;
|
||||
if (socket != null) {
|
||||
try {
|
||||
socket.cancel();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
client = null;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------websocket心跳检测------------------------------------------------
|
||||
private static final long HEART_BEAT_RATE = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
|
||||
private final Handler mHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private void scheduleHeartbeat(long delay) {
|
||||
@@ -326,30 +467,23 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
@Override
|
||||
public void run() {
|
||||
if (destroyed || !connectionEnabled) return;
|
||||
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态");
|
||||
if (client == null) {
|
||||
initSocketClient();
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
Log.i(TAG, "心跳包检测websocket连接状态");
|
||||
// 息屏后不重连、不重排心跳,等亮屏广播唤醒
|
||||
if (!JgyUtils.getInstance().isScreenOn()) {
|
||||
Log.i(TAG, "websocket息屏不重连");
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.isOpen()) {
|
||||
Log.i("JWebSocketClientService", "websocket已连接");
|
||||
if (wsOpen) {
|
||||
Log.i(TAG, "websocket已连接");
|
||||
sendMsg();
|
||||
} else if (client.isClosed()) {
|
||||
Log.i("JWebSocketClientService", "websocket重连中");
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
reconnectWs();
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "reconnectWs off");
|
||||
}
|
||||
}
|
||||
|
||||
//每隔一定的时间,对长连接进行一次心跳检测
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
} else if (attempting) {
|
||||
// 握手进行中,等 onOpen/onFailure 或握手超时回调再决定下一步
|
||||
Log.i(TAG, "websocket握手中");
|
||||
scheduleHeartbeat(HEART_BEAT_RATE);
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "websocket息屏不重连");
|
||||
Log.i(TAG, "websocket重连中");
|
||||
reconnectWs();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -358,6 +492,6 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
|
||||
* 开启重连
|
||||
*/
|
||||
private void reconnectWs() {
|
||||
connectSocket(true);
|
||||
connectSocket();
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,6 @@ import android.widget.TextView;
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
|
||||
import com.alibaba.sdk.android.push.CloudPushService;
|
||||
import com.alibaba.sdk.android.push.CommonCallback;
|
||||
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
|
||||
import com.aoleyun.sn.BuildConfig;
|
||||
import com.aoleyun.sn.R;
|
||||
import com.aoleyun.sn.activity.main.MainActivity;
|
||||
@@ -52,6 +49,7 @@ import com.aoleyun.sn.detection.SensorCheckUtil;
|
||||
import com.aoleyun.sn.gson.GsonUtils;
|
||||
import com.aoleyun.sn.hook.AoleyunActivityController;
|
||||
import com.aoleyun.sn.network.NetInterfaceManager;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.aoleyun.sn.rlog.LogDBManager;
|
||||
import com.aoleyun.sn.service.DetectionService;
|
||||
import com.aoleyun.sn.service.ShakeDetectionService;
|
||||
@@ -117,6 +115,8 @@ public class MainService extends BaseService implements NetworkUtils.OnNetworkSt
|
||||
}
|
||||
}
|
||||
mInternetConnected.onConnected(WiFiAlias);
|
||||
//网络恢复后做一次推送通道状态检测,异常时自动重新注册
|
||||
AliyunPushManager.getInstance().checkChannelStatus();
|
||||
}
|
||||
|
||||
private class TimeTask extends AsyncTask<String, Long, Long> {
|
||||
@@ -132,83 +132,10 @@ public class MainService extends BaseService implements NetworkUtils.OnNetworkSt
|
||||
am.setTime(aLong);
|
||||
//系统时间被修改后重新安排定时关机闹钟
|
||||
PowerOffAlarmUtils.schedule(MainService.this);
|
||||
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// aliyunPushInit();
|
||||
}
|
||||
}, 10000);
|
||||
Log.e(TAG, "getTimeFromNtpServer: " + aLong);
|
||||
}
|
||||
}
|
||||
|
||||
private void aliyunPushInit() {
|
||||
PushServiceFactory.init(this);
|
||||
CloudPushService pushService = PushServiceFactory.getCloudPushService();
|
||||
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 = Utils.getSerial(MainService.this);
|
||||
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");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMessage) {
|
||||
Log.e("AliyunPush", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void checkAliyunPushStatus() {
|
||||
CloudPushService mPushService = PushServiceFactory.getCloudPushService();
|
||||
mPushService.checkPushChannelStatus(new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String response) {
|
||||
Log.e("checkAliyunPushStatus", "onSuccess: " + response);
|
||||
if ("on".equals(response)) {
|
||||
// 当前是打开状态
|
||||
} else {
|
||||
// 当前是关闭状态
|
||||
aliyunPushInit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMessage) {
|
||||
Log.e("checkAliyunPushStatus", "onFailed: errorCode = " + errorCode + " errorMessage = " + errorMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private KillAppListener killAppListener;
|
||||
|
||||
public interface KillAppListener {
|
||||
@@ -394,8 +321,6 @@ public class MainService extends BaseService implements NetworkUtils.OnNetworkSt
|
||||
setStatusbar();
|
||||
setFloatingWindow();
|
||||
|
||||
// aliyunPushInit();
|
||||
|
||||
// TODO: 2026/10/23 从30秒改为1小时
|
||||
Observable.create(killSubscribe)
|
||||
.throttleLast(1, TimeUnit.HOURS)
|
||||
@@ -926,7 +851,8 @@ public class MainService extends BaseService implements NetworkUtils.OnNetworkSt
|
||||
}
|
||||
switch (action) {
|
||||
case Intent.ACTION_SCREEN_ON:
|
||||
checkAliyunPushStatus();
|
||||
//亮屏时做一次推送通道状态检测,通道关闭会自动重新初始化并注册
|
||||
AliyunPushManager.getInstance().checkChannelStatus();
|
||||
break;
|
||||
case Intent.ACTION_SCREEN_OFF:
|
||||
killAppListener.killApp(action);
|
||||
|
||||
@@ -9,9 +9,6 @@ import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.ViewModel;
|
||||
|
||||
import com.alibaba.sdk.android.push.CloudPushService;
|
||||
import com.alibaba.sdk.android.push.CommonCallback;
|
||||
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
|
||||
import com.aoleyun.sn.bean.AdminAppInfo;
|
||||
import com.aoleyun.sn.bean.BaseResponse;
|
||||
import com.aoleyun.sn.bean.ScreenLockState;
|
||||
@@ -19,6 +16,7 @@ import com.aoleyun.sn.bean.StudentsInfo;
|
||||
import com.aoleyun.sn.comm.CommonConfig;
|
||||
import com.aoleyun.sn.comm.JGYActions;
|
||||
import com.aoleyun.sn.network.NetInterfaceManager;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.aoleyun.sn.utils.JgyUtils;
|
||||
import com.aoleyun.sn.utils.SysSettingUtils;
|
||||
import com.aoleyun.sn.utils.URLUtils;
|
||||
@@ -28,8 +26,6 @@ import com.tencent.mmkv.MMKV;
|
||||
import com.trello.rxlifecycle4.RxLifecycle;
|
||||
import com.trello.rxlifecycle4.android.ActivityEvent;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -124,21 +120,11 @@ public class MainServiceModel extends ViewModel {
|
||||
// NetInterfaceManager.getInstance().clearAndAppendTags(tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定推送标签,统一由 AliyunPushManager 处理(含失败重试)
|
||||
*/
|
||||
private void setpushTag(Set<String> tagSets) {
|
||||
String[] tag = new ArrayList<>(tagSets).toArray(new String[tagSets.size()]);
|
||||
CloudPushService pushService = PushServiceFactory.getCloudPushService();
|
||||
pushService.bindTag(CloudPushService.DEVICE_TARGET, tag, null, new CommonCallback() {
|
||||
@Override
|
||||
public void onSuccess(String s) {
|
||||
Log.e("bindTag", "bind tag " + Arrays.toString(tag) + " success\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailed(String errorCode, String errorMsg) {
|
||||
Log.e("bindTag", "bind tag " + Arrays.toString(tag) + " failed." +
|
||||
"errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
|
||||
}
|
||||
});
|
||||
AliyunPushManager.getInstance().bindTags(tagSets);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,7 +48,6 @@ import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
|
||||
import com.aoleyun.sn.BuildConfig;
|
||||
import com.aoleyun.sn.bean.AdminAppInfo;
|
||||
import com.aoleyun.sn.bean.AppID;
|
||||
@@ -69,6 +68,7 @@ import com.aoleyun.sn.disklrucache.CacheHelper;
|
||||
import com.aoleyun.sn.gson.GsonUtils;
|
||||
import com.aoleyun.sn.manager.AllwinnerCubeMdmManager;
|
||||
import com.aoleyun.sn.network.NetInterfaceManager;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.aoleyun.sn.receiver.BootReceiver;
|
||||
import com.aoleyun.sn.service.GuardService;
|
||||
import com.aoleyun.sn.service.StepService;
|
||||
@@ -3126,7 +3126,7 @@ public class JgyUtils {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("sn", Utils.getSerial(context));
|
||||
jsonObject.addProperty("mac", Utils.getAndroid10MAC(mContext));
|
||||
jsonObject.addProperty("jpush_id", PushServiceFactory.getCloudPushService().getDeviceId());
|
||||
jsonObject.addProperty("jpush_id", AliyunPushManager.getDeviceId());
|
||||
jsonObject.addProperty("devices_version", Utils.getCustomVersion());
|
||||
jsonObject.addProperty("appstore_version", BuildConfig.VERSION_NAME);
|
||||
jsonObject.addProperty("store_version", Utils.getAppVersionName(PackageNames.APPSTORE, mContext));
|
||||
|
||||
@@ -1531,6 +1531,66 @@ public class SysSettingUtils {
|
||||
menus.add("kids_mode");
|
||||
}
|
||||
|
||||
int wlan = jsonObject.get("wlan").getAsInt();
|
||||
if (wlan == 0) {
|
||||
menus.add("wlan");
|
||||
}
|
||||
|
||||
int connected_devices = jsonObject.get("connected_devices").getAsInt();
|
||||
if (connected_devices == 0) {
|
||||
menus.add("connected_devices");
|
||||
}
|
||||
|
||||
int wallpaper = jsonObject.get("wallpaper").getAsInt();
|
||||
if (wallpaper == 0) {
|
||||
menus.add("wallpaper");
|
||||
}
|
||||
|
||||
int display = jsonObject.get("display").getAsInt();
|
||||
if (display == 0) {
|
||||
menus.add("display");
|
||||
}
|
||||
|
||||
int sound = jsonObject.get("sound").getAsInt();
|
||||
if (sound == 0) {
|
||||
menus.add("sound");
|
||||
}
|
||||
|
||||
int location = jsonObject.get("location").getAsInt();
|
||||
if (location == 0) {
|
||||
menus.add("location");
|
||||
}
|
||||
|
||||
int storage = jsonObject.get("storage").getAsInt();
|
||||
if (storage == 0) {
|
||||
menus.add("storage");
|
||||
}
|
||||
|
||||
int nav_bar_mode = jsonObject.get("nav_bar_mode").getAsInt();
|
||||
if (nav_bar_mode == 0) {
|
||||
menus.add("nav_bar_mode");
|
||||
}
|
||||
|
||||
int system_more_setting = jsonObject.get("system_more_setting").getAsInt();
|
||||
if (system_more_setting == 0) {
|
||||
menus.add("system");
|
||||
}
|
||||
|
||||
int system_updates = jsonObject.get("system_updates").getAsInt();
|
||||
if (system_updates == 0) {
|
||||
menus.add("system_updates");
|
||||
}
|
||||
|
||||
int feedback = jsonObject.get("feedback").getAsInt();
|
||||
if (feedback == 0) {
|
||||
menus.add("feedback");
|
||||
}
|
||||
|
||||
int about = jsonObject.get("about").getAsInt();
|
||||
if (about == 0) {
|
||||
menus.add("about");
|
||||
}
|
||||
|
||||
Log.e(TAG, "setSettingsMenuShow: " + menus);
|
||||
AndroidSettingsWriter.putString(context, AndroidSettingsWriter.NAMESPACE_SYSTEM, CommonConfig.AOLE_SETTINGS_DISALLOW, String.join(",", menus));
|
||||
}
|
||||
|
||||
@@ -51,11 +51,11 @@ import android.widget.Toast;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.annotation.VisibleForTesting;
|
||||
|
||||
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
|
||||
import com.aoleyun.sn.BuildConfig;
|
||||
import com.aoleyun.sn.R;
|
||||
import com.aoleyun.sn.comm.CommonConfig;
|
||||
import com.aoleyun.sn.manager.AllwinnerCubeMdmManager;
|
||||
import com.aoleyun.sn.push.AliyunPushManager;
|
||||
import com.arialyy.aria.core.Aria;
|
||||
import com.blankj.utilcode.util.FileUtils;
|
||||
import com.google.gson.JsonElement;
|
||||
@@ -67,6 +67,7 @@ import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.qrcode.QRCodeWriter;
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||||
import com.hjq.toast.Toaster;
|
||||
import com.onyx.android.sdk.utils.SystemPropertiesUtil;
|
||||
import com.tencent.mmkv.MMKV;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
@@ -1534,7 +1535,7 @@ public class Utils {
|
||||
|
||||
public static String getOtherInfo() {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("push_id", PushServiceFactory.getCloudPushService().getDeviceId());
|
||||
jsonObject.addProperty("push_id", AliyunPushManager.getDeviceId());
|
||||
String jsonString = jsonObject.toString();
|
||||
Log.e(TAG, "getOtherInfo: push_id = " + jsonString);
|
||||
return jsonString;
|
||||
@@ -1846,13 +1847,14 @@ public class Utils {
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.U1302Platform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G128TPlatform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.QualcommPlatform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.DX11Platform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G12NLPlatform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G122JPlatform
|
||||
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.TDT65Platform
|
||||
) {
|
||||
return Utils.getProperty("ro.build.display.id", "获取失败");
|
||||
} else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.QualcommPlatform) {
|
||||
return SystemPropertiesUtil.getBuildId();
|
||||
} else {
|
||||
return Utils.getProperty("ro.custom.build.version", "获取失败");
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ buildscript {
|
||||
maven { url 'https://maven.aliyun.com/repository/jcenter' }
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
maven { url 'https://maven.aliyun.com/repository/google' }
|
||||
maven { url "https://repo.boox.com/repository/maven-public/" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -61,6 +62,7 @@ allprojects {
|
||||
maven { url 'https://maven.aliyun.com/repository/jcenter' }
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
maven { url 'https://maven.aliyun.com/repository/google' }
|
||||
maven { url "https://repo.boox.com/repository/maven-public/" }
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
|
||||
Reference in new issue
Block a user