feat(push): 升级下载与启动请求错峰,优化网络去重
This commit is contained in:
1 parent
7e169eb462
commit
14ff2c42ae
13 files changed
+573
-488
No files matched your search
@@ -63,13 +63,13 @@ public class BaseApplication extends Application {
|
||||
if (BuildConfig.DEBUG) {
|
||||
// ApkUtils.openApp(this, "com.android.settings");
|
||||
//静音
|
||||
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
|
||||
int ringMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_RING);
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_RING, ringMax, 0);
|
||||
int musicMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_MUSIC);
|
||||
int voiceMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_VOICE_CALL);
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, voiceMax, 0);
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicMax, 0); //音乐音量
|
||||
// AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
|
||||
// int ringMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_RING);
|
||||
// audioManager.setStreamVolume(AudioManager.STREAM_RING, ringMax, 0);
|
||||
// int musicMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_MUSIC);
|
||||
// int voiceMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_VOICE_CALL);
|
||||
// audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, voiceMax, 0);
|
||||
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicMax, 0); //音乐音量
|
||||
Log.e(TAG, "debugTest: " + getExternalCacheDir());
|
||||
Log.e(TAG, "debugTest: " + getExternalFilesDir("cache"));
|
||||
Log.e(TAG, "debugTest: " + getCacheDir());
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Deprecated
|
||||
public class AppRunTimeBean implements Serializable {
|
||||
private static final long serialVersionUID = 3699088127005434759L;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.fuying.sn.bean.PartTime;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class AppTimeControl implements Serializable {
|
||||
private static final long serialVersionUID = -240088037272271214L;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.fuying.sn.bean.PartTime;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class MachineControl implements Serializable {
|
||||
private static final long serialVersionUID = 8554412088242960068L;
|
||||
|
||||
|
||||
@@ -287,41 +287,28 @@ public class ControlManager {
|
||||
try {
|
||||
//蓝牙开关
|
||||
int setting_bht = changeNum(settings.getSetting_bht());
|
||||
//总开关
|
||||
int setting_bhtvideo = changeNum(settings.getSetting_bhtvideo());
|
||||
//蓝牙音频开关
|
||||
int setting_bluetooth = changeNum(settings.getSetting_bluetooth());
|
||||
// int setting_bhtvideo = changeNum(settings.getSetting_bhtvideo());
|
||||
//蓝牙传输开关
|
||||
boolean aole_bht_forbid_on = Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BHT_FORBID_ON, setting_bht);
|
||||
//写入系统数据库
|
||||
Log.e("SystemSetting", "aole_bht_forbid_on:" + aole_bht_forbid_on);
|
||||
// int setting_bluetooth = changeNum(settings.getSetting_bluetooth());
|
||||
|
||||
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
if (aole_bht_forbid_on) {
|
||||
//成功
|
||||
if (null == mBluetoothAdapter) {
|
||||
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
//获取默认蓝牙适配器
|
||||
}
|
||||
if (setting_bht == 0) {
|
||||
//蓝牙总开关开启
|
||||
String setting_context = settings.getSetting_context();
|
||||
if (setting_bhtvideo == 0) {
|
||||
if (null != setting_context && !"".equals(setting_context) && !" ".equals(setting_context) && !"null".equals(setting_context)) {
|
||||
Log.e("SystemSetting", "setting_context:" + setting_context);
|
||||
Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, setting_context);
|
||||
} else {
|
||||
Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, "Empty");
|
||||
}
|
||||
} else if (setting_bhtvideo == 1) {
|
||||
Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, "Empty");
|
||||
}
|
||||
Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BT_FORBID_ON, setting_bluetooth);
|
||||
} else {
|
||||
mBluetoothAdapter.disable();
|
||||
//设置关闭时关闭蓝牙
|
||||
}
|
||||
//写入系统数据库
|
||||
Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BHT_FORBID_ON, setting_bht);
|
||||
Log.e("SystemSetting", "aole_bht_forbid_on:" + setting_bht);
|
||||
if (setting_bht == 1) {
|
||||
//管控蓝牙,关闭蓝牙总开关
|
||||
disableBluetooth();
|
||||
}
|
||||
//蓝牙总开关开启
|
||||
// String setting_context = settings.getSetting_context();
|
||||
// if (setting_bhtvideo == 0 && !TextUtils.isEmpty(setting_context)
|
||||
// && !" ".equals(setting_context) && !"null".equals(setting_context)) {
|
||||
// Log.e("SystemSetting", "setting_context:" + setting_context);
|
||||
// Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, setting_context);
|
||||
// } else {
|
||||
// Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, null);
|
||||
// }
|
||||
// Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BT_FORBID_ON, setting_bluetooth);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "setBluetooth: " + e.getMessage());
|
||||
}
|
||||
@@ -329,27 +316,33 @@ public class ControlManager {
|
||||
|
||||
private void setBluetooth(int state) {
|
||||
try {
|
||||
boolean aole_bht_forbid_on = Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BHT_FORBID_ON, state);
|
||||
//写入系统数据库
|
||||
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();
|
||||
//获取默认蓝牙适配器
|
||||
}
|
||||
//蓝牙总开关开启
|
||||
Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, "Empty");
|
||||
Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BT_FORBID_ON, state);
|
||||
mBluetoothAdapter.disable();
|
||||
Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BHT_FORBID_ON, state);
|
||||
Log.e(TAG, "aole_bht_forbid_on:" + state);
|
||||
//蓝牙音频管控置空
|
||||
// Settings.System.putString(mResolver, CommonConfig.AOLE_ACTION_BHTVIDEO_FORBID_ON, null);
|
||||
// Settings.System.putInt(mResolver, CommonConfig.AOLE_ACTION_BT_FORBID_ON, state);
|
||||
if (state == 1) {
|
||||
//设置关闭时关闭蓝牙
|
||||
disableBluetooth();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "setBluetooth: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭蓝牙总开关,仅在需要禁用蓝牙时调用
|
||||
*/
|
||||
private void disableBluetooth() {
|
||||
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
if (null != bluetoothAdapter) {
|
||||
bluetoothAdapter.disable();
|
||||
} else {
|
||||
Log.e(TAG, "disableBluetooth: BluetoothAdapter is NULL");
|
||||
}
|
||||
}
|
||||
|
||||
private void setHotspot(SystemSettings settings) {
|
||||
try {
|
||||
int setting_hotspot = changeNum(settings.getSetting_hotspot());//热点
|
||||
|
||||
@@ -101,7 +101,9 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
@@ -132,6 +134,15 @@ public class NetInterfaceManager {
|
||||
|
||||
private static final RxCacheManager CACHE_MANAGER = RxCacheManager.getInstance();
|
||||
|
||||
/**
|
||||
* 同 key 的"在飞行中"网络请求。
|
||||
* <p>
|
||||
* 缓存未命中时,若同一时刻有多处订阅同一个 key(例如推送刷新与网络重连重叠、
|
||||
* 时间管控刷新与界面刷新重叠),只真正发一次网络请求,其余订阅复用同一次结果,
|
||||
* 避免同一接口被打出多份重复请求。
|
||||
*/
|
||||
private static final ConcurrentHashMap<String, Observable<?>> IN_FLIGHT_REQUESTS = new ConcurrentHashMap<>();
|
||||
|
||||
public static void clearAllCache() {
|
||||
Log.e(TAG, "clearAllCache: ");
|
||||
CACHE_MANAGER.clearAllCache();
|
||||
@@ -140,6 +151,16 @@ public class NetInterfaceManager {
|
||||
public static void removeCache(String key) {
|
||||
Log.e(TAG, "removeCache: key = " + key);
|
||||
CACHE_MANAGER.removeCache(key);
|
||||
// 内存缓存与磁盘缓存共用同一个 key,这里一并清理。
|
||||
// 否则内存缓存被清后,下一次调用会先把磁盘里的旧数据兜底发射出去,
|
||||
// 出现一段"配置回退到旧值"的窗口(推送刷新、解绑授权等场景)。
|
||||
try {
|
||||
if (INSTANCE != null && INSTANCE.mCacheHelper != null) {
|
||||
INSTANCE.mCacheHelper.remove(key);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "removeCache: remove disk cache error = " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
//缓存过期时间1秒
|
||||
@@ -242,6 +263,39 @@ public class NetInterfaceManager {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 把一次网络请求包装成"多订阅者共享同一次请求"的 Observable。
|
||||
* <p>
|
||||
* 同一个 key 若已有在飞行中的请求,直接复用;否则发起新请求,
|
||||
* 并在请求结束(成功/失败/取消)后清理在飞行标记,允许下一次重新请求。
|
||||
*
|
||||
* @param cacheKey 请求唯一标识
|
||||
* @param networkObservable 原始网络请求
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> Observable<T> joinInFlight(String cacheKey, Observable<T> networkObservable) {
|
||||
Observable<T> inFlight = (Observable<T>) IN_FLIGHT_REQUESTS.get(cacheKey);
|
||||
if (inFlight != null) {
|
||||
Log.e(TAG, "joinInFlight: reuse in-flight request " + cacheKey);
|
||||
return inFlight;
|
||||
}
|
||||
// self 用于在 doFinally 中精确移除"自己"这一条,避免误删后放入的新请求
|
||||
final AtomicReference<Observable<T>> self = new AtomicReference<>();
|
||||
Observable<T> request = networkObservable
|
||||
.doFinally(() -> {
|
||||
Observable<T> current = self.get();
|
||||
if (current != null) {
|
||||
IN_FLIGHT_REQUESTS.remove(cacheKey, current);
|
||||
}
|
||||
})
|
||||
// replay(1) + refCount:并发订阅共享同一次请求与同一个结果
|
||||
.replay(1)
|
||||
.refCount();
|
||||
self.set(request);
|
||||
Observable<T> existing = (Observable<T>) IN_FLIGHT_REQUESTS.putIfAbsent(cacheKey, request);
|
||||
return existing != null ? existing : request;
|
||||
}
|
||||
|
||||
/**
|
||||
* 极简调用:仅需 网络请求Observable + 缓存过期时间
|
||||
*
|
||||
@@ -252,7 +306,7 @@ public class NetInterfaceManager {
|
||||
public static <T> Observable<T> withCache(Observable<T> networkObservable, String cacheKey, long expireTimeMillis) {
|
||||
return Observable.defer(() -> {
|
||||
// Log.e(TAG, "withCache: cacheKey = " + cacheKey);
|
||||
// 1. 读取缓存
|
||||
// 1. 命中未过期缓存直接返回,不再请求网络
|
||||
T cacheData = CACHE_MANAGER.getCache(cacheKey);
|
||||
if (cacheData != null) {
|
||||
Log.e(TAG, "withCache: getCache " + cacheKey);
|
||||
@@ -260,10 +314,10 @@ public class NetInterfaceManager {
|
||||
}
|
||||
|
||||
Log.e(TAG, "withCache: request " + cacheKey);
|
||||
// 2. 无缓存则发起网络请求,成功后缓存
|
||||
return networkObservable
|
||||
// 2. 无缓存则发起网络请求(同 key 并发只发一次),成功后缓存
|
||||
return joinInFlight(cacheKey, networkObservable
|
||||
.subscribeOn(Schedulers.io())
|
||||
.doOnNext(data -> CACHE_MANAGER.saveCache(cacheKey, data, expireTimeMillis));
|
||||
.doOnNext(data -> CACHE_MANAGER.saveCache(cacheKey, data, expireTimeMillis)));
|
||||
})
|
||||
.subscribeOn(Schedulers.io()) // 缓存IO切到子线程
|
||||
.observeOn(AndroidSchedulers.mainThread());
|
||||
@@ -288,30 +342,33 @@ public class NetInterfaceManager {
|
||||
return Observable.<BaseResponse<T>>create(emitter -> {
|
||||
Log.e(TAG, "withMultiLevelCache: cacheKey = " + cacheKey);
|
||||
|
||||
// 1. 优先从内存缓存获取
|
||||
// 1. 内存缓存未过期,直接返回,不再请求网络
|
||||
// (内存缓存的 TTL 已经表达了"数据新鲜",命中还请求等于白白打一次接口)
|
||||
BaseResponse<T> memoryCache = CACHE_MANAGER.getCache(cacheKey);
|
||||
if (memoryCache != null) {
|
||||
Log.e(TAG, "withMultiLevelCache: hit memory cache");
|
||||
Log.e(TAG, "withMultiLevelCache: hit memory cache, skip network");
|
||||
emitter.onNext(memoryCache);
|
||||
} else {
|
||||
// 2. 内存未命中,从磁盘缓存获取
|
||||
try {
|
||||
String diskCacheJson = INSTANCE.mCacheHelper.getAsString(cacheKey);
|
||||
if (!TextUtils.isEmpty(diskCacheJson)) {
|
||||
Log.e(TAG, "withMultiLevelCache: hit disk cache");
|
||||
BaseResponse<T> diskCache = GsonUtils.toJavaObject(diskCacheJson, type);
|
||||
if (diskCache != null) {
|
||||
emitter.onNext(diskCache);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "withMultiLevelCache: read disk cache error", e);
|
||||
}
|
||||
emitter.onComplete();
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. 始终请求网络数据以同步更新
|
||||
// 2. 内存未命中,先用磁盘缓存兜底展示
|
||||
try {
|
||||
String diskCacheJson = INSTANCE.mCacheHelper.getAsString(cacheKey);
|
||||
if (!TextUtils.isEmpty(diskCacheJson)) {
|
||||
Log.e(TAG, "withMultiLevelCache: hit disk cache");
|
||||
BaseResponse<T> diskCache = GsonUtils.toJavaObject(diskCacheJson, type);
|
||||
if (diskCache != null) {
|
||||
emitter.onNext(diskCache);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "withMultiLevelCache: read disk cache error", e);
|
||||
}
|
||||
|
||||
// 3. 请求网络刷新(同 key 并发只发一次)
|
||||
Log.e(TAG, "withMultiLevelCache: request from network");
|
||||
networkObservable
|
||||
joinInFlight(cacheKey, networkObservable)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseResponse<T>>() {
|
||||
|
||||
@@ -44,6 +44,7 @@ import com.fuying.sn.utils.FileUtils;
|
||||
import com.fuying.sn.utils.JgyUtils;
|
||||
import com.fuying.sn.utils.SPUtils;
|
||||
import com.fuying.sn.utils.ServiceAliveUtils;
|
||||
import com.fuying.sn.utils.TimeUtils;
|
||||
import com.fuying.sn.utils.ToastUtil;
|
||||
import com.fuying.sn.utils.Utils;
|
||||
import com.google.gson.JsonElement;
|
||||
@@ -109,6 +110,39 @@ public class PushManager {
|
||||
*/
|
||||
private static final String KEY_PUSH_REFRESH = "push_config_refresh";
|
||||
|
||||
/**
|
||||
* 推送是全量下发,所有设备几乎同一时刻收到并触发刷新,
|
||||
* 这里在原有延时上再叠加 [0, 30s) 的随机抖动,避免整批设备集中请求把服务端打挂。
|
||||
*/
|
||||
private static final long PUSH_REFRESH_JITTER = 30 * 1000L;
|
||||
|
||||
/**
|
||||
* 自身升级包的下载错峰上限:窗口内最多随机延后 1 小时才开始下载升级包。
|
||||
* 自身升级会导致全量设备重启并在重启后集中请求,所以错峰窗口要足够长。
|
||||
*/
|
||||
private static final long UPGRADE_DOWNLOAD_MAX_SPREAD = 60 * 60 * 1000L;
|
||||
|
||||
/**
|
||||
* 其它应用安装包的下载错峰上限:1 分钟内随机错峰即可,
|
||||
* 只为了避免整批设备同一时刻下载,不影响白天正常安装。
|
||||
*/
|
||||
private static final long OTHER_APP_DOWNLOAD_MAX_SPREAD = 60 * 1000L;
|
||||
|
||||
/**
|
||||
* 静默升级下载预留的窗口余量:至少留 10 分钟,保证下载能落在窗口内完成。
|
||||
*/
|
||||
private static final long UPGRADE_DOWNLOAD_WINDOW_MARGIN = 10 * 60 * 1000L;
|
||||
|
||||
/**
|
||||
* 待执行的静默升级任务(窗口外收到推送、或进程被杀时留存,进入窗口后错峰执行)。
|
||||
*/
|
||||
private static final String KEY_PENDING_UPGRADE = "pending_force_install_apk";
|
||||
|
||||
/**
|
||||
* 已排期但尚未开始下载的升级任务标记,避免轮询重复排期导致重复下载。
|
||||
*/
|
||||
private boolean mUpgradeScheduled = false;
|
||||
|
||||
private Handler mSyncHandler;
|
||||
private Runnable mPollRunnable;
|
||||
private Runnable mDebounceRunnable;
|
||||
@@ -609,8 +643,9 @@ public class PushManager {
|
||||
// NetInterfaceManager.getInstance().getMachineTimeControl();
|
||||
// NetInterfaceManager.getInstance().getSnTimeControl();
|
||||
TimeManager.getInstance().getTimeControl();
|
||||
NetInterfaceManager.getInstance().getAllappPackage();
|
||||
}
|
||||
}, 2345);
|
||||
}, 2345 + TimeUtils.randomDelay(0, PUSH_REFRESH_JITTER));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -629,6 +664,8 @@ public class PushManager {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.e(TAG, "polling tick -> updateUserSettings");
|
||||
// 窗口外收到、或进程被杀而遗留的自身升级任务,进入窗口后在这里被重新拾起
|
||||
runPendingUpgrade();
|
||||
updateUserSettings();
|
||||
if (mSyncHandler != null) {
|
||||
mSyncHandler.postDelayed(this, POLLING_INTERVAL);
|
||||
@@ -774,16 +811,16 @@ public class PushManager {
|
||||
}
|
||||
|
||||
private void setVolume(String extras) {
|
||||
JsonObject jsonObject = GsonUtils.getJsonObject(extras);
|
||||
int setting_volume = jsonObject.get("setting_volume").getAsInt();
|
||||
//获取系统的Audio管理者
|
||||
AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
//最大音量
|
||||
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
|
||||
//当前音量
|
||||
// int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
|
||||
int currentVolume = (int) ((1.0f * maxVolume / 100) * setting_volume);
|
||||
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
|
||||
// JsonObject jsonObject = GsonUtils.getJsonObject(extras);
|
||||
// int setting_volume = jsonObject.get("setting_volume").getAsInt();
|
||||
// //获取系统的Audio管理者
|
||||
// AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
// //最大音量
|
||||
// int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
|
||||
// //当前音量
|
||||
//// int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
|
||||
// int currentVolume = (int) ((1.0f * maxVolume / 100) * setting_volume);
|
||||
// mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
|
||||
}
|
||||
|
||||
private int changeNum(int paramInt) {
|
||||
@@ -914,31 +951,165 @@ public class PushManager {
|
||||
return;
|
||||
}
|
||||
long app_version_code = extra.get("app_version_code").getAsLong();
|
||||
PackageInfo info = null;
|
||||
PackageManager pm = mContext.getPackageManager();
|
||||
try {
|
||||
info = pm.getPackageInfo(packages, 0);
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
if (!isVersionLowerThan(packages, app_version_code)) {
|
||||
Log.e(TAG, "intallApk: it's up to date , no need upgrade");
|
||||
return;
|
||||
}
|
||||
if (null != info) {
|
||||
long appVersionCode;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
appVersionCode = info.getLongVersionCode();
|
||||
} else {
|
||||
appVersionCode = info.versionCode;
|
||||
}
|
||||
if (appVersionCode < app_version_code) {
|
||||
Log.e(TAG, "intallApk: " + "need to upgrade");
|
||||
FileUtils.ariaDownload(mContext, url, extra);
|
||||
} else
|
||||
Log.e(TAG, "intallApk: " + "it's up to date , no need upgrade");
|
||||
Log.e(TAG, "intallApk: need to upgrade");
|
||||
if (packages.equals(mContext.getPackageName())) {
|
||||
// 自身升级:全量设备都会重启且重启后集中请求,只在夜间窗口(23:00-05:00)内长错峰执行
|
||||
enqueueUpgrade(jsonString);
|
||||
} else {
|
||||
Log.e(TAG, "intallApk: " + "not installed , upgrade");
|
||||
FileUtils.ariaDownload(mContext, url, extra);
|
||||
// 其它应用:1 分钟内短错峰即可,不影响白天正常安装
|
||||
downloadWithSpread(extra, url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某个包当前已安装的版本是否仍低于目标版本(即仍需升级)。
|
||||
* 包未安装时视为需要安装。
|
||||
*
|
||||
* @param packages 包名
|
||||
* @param targetVersionCode 推送里携带的目标版本号
|
||||
*/
|
||||
private boolean isVersionLowerThan(String packages, long targetVersionCode) {
|
||||
PackageInfo info;
|
||||
try {
|
||||
info = mContext.getPackageManager().getPackageInfo(packages, 0);
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
// 未安装,视为需要安装
|
||||
return true;
|
||||
}
|
||||
long localVersionCode;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
localVersionCode = info.getLongVersionCode();
|
||||
} else {
|
||||
localVersionCode = info.versionCode;
|
||||
}
|
||||
return localVersionCode < targetVersionCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验遗留的自身升级任务是否仍然有必要执行。
|
||||
* <p>
|
||||
* 任务落盘到真正执行之间可能隔了几个小时,这期间用户可能已经手动升级了客户端、
|
||||
* 或通过其它渠道升级到位,此时必须丢弃任务,避免窗口一到又下载安装一次旧包。
|
||||
*/
|
||||
private boolean isPendingUpgradeStillNeeded(String jsonString) {
|
||||
try {
|
||||
JsonObject extra = GsonUtils.getJsonObject(jsonString);
|
||||
String packages = extra.get("package").getAsString();
|
||||
long targetVersionCode = extra.get("app_version_code").getAsLong();
|
||||
return isVersionLowerThan(packages, targetVersionCode);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "isPendingUpgradeStillNeeded: 解析升级信息失败 " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 其它应用安装包下载:在 {@link #OTHER_APP_DOWNLOAD_MAX_SPREAD} 内随机错峰,
|
||||
* 避免整批设备同时下载把服务端带宽打满。
|
||||
*/
|
||||
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() {
|
||||
@Override
|
||||
public void run() {
|
||||
FileUtils.ariaDownload(mContext, url, extra);
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自身升级任务入队。
|
||||
* <p>
|
||||
* 只在夜间窗口(23:00-05:00)执行,任务先落盘再择机执行,
|
||||
* 这样窗口外收到推送、或进程被杀都不会丢任务。
|
||||
*/
|
||||
private void enqueueUpgrade(String jsonString) {
|
||||
if (TextUtils.isEmpty(jsonString)) {
|
||||
return;
|
||||
}
|
||||
mMMKV.encode(KEY_PENDING_UPGRADE, jsonString);
|
||||
runPendingUpgrade();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行待处理的自身升级任务。
|
||||
* <p>
|
||||
* 关键点:升级包是全量下发的,如果所有设备收到推送后立刻同时下载、同时重启,
|
||||
* 重启后又会同时请求接口,服务端会被瞬间打挂。这里做了两件事:
|
||||
* <ul>
|
||||
* <li>窗口限制:只在 23:00-05:00 之间下载安装;窗口外顺延到下一个窗口(由轮询兜底)。</li>
|
||||
* <li>错峰:在窗口剩余时间内随机取一个时刻开始下载,把整批设备的下载与重启摊开。</li>
|
||||
* </ul>
|
||||
* 其它应用的安装不在这里处理,见 {@link #downloadWithSpread(JsonObject, String)}。
|
||||
*/
|
||||
private void runPendingUpgrade() {
|
||||
if (mUpgradeScheduled) {
|
||||
Log.e(TAG, "runPendingUpgrade: 已有升级任务等待执行,忽略本次");
|
||||
return;
|
||||
}
|
||||
String jsonString = mMMKV.decodeString(KEY_PENDING_UPGRADE, "");
|
||||
if (TextUtils.isEmpty(jsonString)) {
|
||||
return;
|
||||
}
|
||||
// 任务从落盘到真正执行可能隔了好几个小时,先复校验版本:
|
||||
// 这期间用户完全可能已经手动升级了客户端,残留任务必须丢弃,
|
||||
// 否则窗口一到还会把旧包重新下载、重新静默安装一次。
|
||||
if (!isPendingUpgradeStillNeeded(jsonString)) {
|
||||
Log.e(TAG, "runPendingUpgrade: 本地版本已不低于目标版本(可能已手动升级),丢弃遗留任务");
|
||||
mMMKV.remove(KEY_PENDING_UPGRADE);
|
||||
return;
|
||||
}
|
||||
if (!TimeUtils.isInNightWindow()) {
|
||||
Log.e(TAG, "runPendingUpgrade: 不在静默升级窗口(23:00-05:00),顺延 "
|
||||
+ (TimeUtils.millisToNextNightWindow() / 1000) + " 秒后的窗口");
|
||||
return;
|
||||
}
|
||||
// 窗口内:在 "窗口剩余时间 - 下载余量" 范围内随机延时,实现多设备错峰
|
||||
long usable = TimeUtils.millisToNightWindowEnd() - UPGRADE_DOWNLOAD_WINDOW_MARGIN;
|
||||
long spread = Math.min(UPGRADE_DOWNLOAD_MAX_SPREAD, Math.max(usable, 0));
|
||||
long delay = TimeUtils.randomDelay(0, spread + 1);
|
||||
mUpgradeScheduled = true;
|
||||
mMMKV.remove(KEY_PENDING_UPGRADE);
|
||||
Log.e(TAG, "runPendingUpgrade: 错峰 " + (delay / 1000) + " 秒后开始下载升级包");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mUpgradeScheduled = false;
|
||||
// 从排期到执行之间最长还有 1 小时,期间用户可能已手动升级,这里再校验一次
|
||||
if (!isPendingUpgradeStillNeeded(jsonString)) {
|
||||
Log.e(TAG, "runPendingUpgrade: 本地版本已不低于目标版本(可能已手动升级),放弃本次升级");
|
||||
return;
|
||||
}
|
||||
if (!TextUtils.isEmpty(jsonString) && !TimeUtils.isInNightWindow()) {
|
||||
// 极端情况下延时期间跨出了窗口,重新入队等下一个窗口
|
||||
Log.e(TAG, "runPendingUpgrade: 已超出升级窗口,顺延到下一个窗口");
|
||||
enqueueUpgrade(jsonString);
|
||||
return;
|
||||
}
|
||||
JsonObject extra;
|
||||
String url;
|
||||
try {
|
||||
extra = GsonUtils.getJsonObject(jsonString);
|
||||
url = extra.get("url").getAsString();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "runPendingUpgrade: 解析升级信息失败 " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
if (TextUtils.isEmpty(url)) {
|
||||
Log.e(TAG, "runPendingUpgrade: 升级包地址为空,放弃本次升级");
|
||||
return;
|
||||
}
|
||||
Log.e(TAG, "runPendingUpgrade: 开始下载升级包 " + url);
|
||||
FileUtils.ariaDownload(mContext, url, extra);
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
synchronized private void unintallApk(String jsonString) {
|
||||
JsonObject object = GsonUtils.getJsonObject(jsonString);
|
||||
String packageName = object.get("app_package").getAsString();
|
||||
|
||||
@@ -32,7 +32,6 @@ import com.fuying.sn.push.PushManager;
|
||||
import com.fuying.sn.receiver.APKinstallReceiver;
|
||||
import com.fuying.sn.receiver.BootReceiver;
|
||||
import com.fuying.sn.utils.SPUtils;
|
||||
import com.fuying.sn.utils.TimeUtils;
|
||||
import com.fuying.sn.utils.Utils;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.tencent.mmkv.MMKV;
|
||||
@@ -60,12 +59,9 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
|
||||
public static final String ACTION_LOCK = "LockScreenReceiver_lockscreen";
|
||||
public static final String ACTION_UNLOCK = "LockScreenReceiver_unlockscreen";
|
||||
public static final String ACTION_UPDATE = "TimeChangedReceiver_update";
|
||||
private static final String DEFAULT_PASSWORD = "0000";
|
||||
private WindowManager windowManager;
|
||||
private View topView;
|
||||
private boolean screenlocked = false;
|
||||
private boolean timelocked = false;
|
||||
|
||||
/**
|
||||
* 本地"已用密码解除锁屏"标记。
|
||||
@@ -185,10 +181,8 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
pwdUnlocked = false;
|
||||
setLockedState(is_screen_lock);
|
||||
} else {
|
||||
if (!timelocked) {
|
||||
hideFloatingWindow();
|
||||
}
|
||||
screenlocked = false;
|
||||
// 服务端明确返回非锁定(未绑定/未登录等):直接解锁
|
||||
hideFloatingWindow();
|
||||
SPUtils.put(ManagerService.this, LOCK_STATE, 0);
|
||||
}
|
||||
}
|
||||
@@ -207,16 +201,10 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
|
||||
private void setLockedState(int lockedState) {
|
||||
if (lockedState == 1) {
|
||||
if (!timelocked) {
|
||||
showFloatingWindow("屏幕已锁定");
|
||||
}
|
||||
screenlocked = true;
|
||||
showFloatingWindow("屏幕已锁定");
|
||||
SPUtils.put(ManagerService.this, LOCK_STATE, 1);
|
||||
} else {
|
||||
if (!timelocked) {
|
||||
hideFloatingWindow();
|
||||
}
|
||||
screenlocked = false;
|
||||
hideFloatingWindow();
|
||||
SPUtils.put(ManagerService.this, LOCK_STATE, 0);
|
||||
}
|
||||
}
|
||||
@@ -240,63 +228,74 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
// Log.e(TAG, "showFloatingWindow: debug mode skip");
|
||||
// return;
|
||||
// }
|
||||
if (Settings.canDrawOverlays(this)) {
|
||||
// 获取WindowManager服务
|
||||
if (null == windowManager) {
|
||||
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
|
||||
}
|
||||
DisplayMetrics dm = new DisplayMetrics();
|
||||
windowManager.getDefaultDisplay().getRealMetrics(dm);
|
||||
int width = dm.widthPixels; // 屏幕宽度(像素)
|
||||
int height = dm.heightPixels; // 屏幕高度(像素)
|
||||
// 新建悬浮窗控件
|
||||
final Button button = new Button(getApplicationContext());
|
||||
button.setText("霸屏测试");
|
||||
button.setAlpha(0.9f);
|
||||
button.setBackgroundColor(Color.BLACK);
|
||||
button.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (!Settings.canDrawOverlays(this)) {
|
||||
// 没有悬浮窗权限时原来会静默返回,出问题时完全无迹可查
|
||||
Log.e(TAG, "showFloatingWindow: no overlay permission, skip. name=" + name);
|
||||
return;
|
||||
}
|
||||
// 获取WindowManager服务
|
||||
if (null == windowManager) {
|
||||
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
|
||||
}
|
||||
DisplayMetrics dm = new DisplayMetrics();
|
||||
windowManager.getDefaultDisplay().getRealMetrics(dm);
|
||||
int width = dm.widthPixels; // 屏幕宽度(像素)
|
||||
int height = dm.heightPixels; // 屏幕高度(像素)
|
||||
// 新建悬浮窗控件
|
||||
final Button button = new Button(getApplicationContext());
|
||||
button.setText("霸屏测试");
|
||||
button.setAlpha(0.9f);
|
||||
button.setBackgroundColor(Color.BLACK);
|
||||
button.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
// windowManager.removeView(button);
|
||||
}
|
||||
});
|
||||
if (null == topView) {
|
||||
topView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_screen_lock, null);
|
||||
}
|
||||
});
|
||||
if (null != topView) {
|
||||
if (topView.isAttachedToWindow()) {
|
||||
// 已在屏:只刷新文案,避免重复 addView
|
||||
initTopView(topView, name);
|
||||
} else {
|
||||
if ("added".equals(topView.getTag())) {
|
||||
initTopView(topView, name);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// topView.setAlpha(0.8f);
|
||||
// 设置LayoutParam
|
||||
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
layoutParams.type = WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
|
||||
//TYPE_SYSTEM_OVERLAY可以下滑通知栏
|
||||
// 引用还在但窗口已被系统移除(被其他窗口顶掉/系统回收):
|
||||
// 原实现会一直复用这个已不在屏上的 View,导致锁屏"看起来失效"
|
||||
Log.e(TAG, "showFloatingWindow: topView detached, rebuild it.");
|
||||
removeTopViewSafely();
|
||||
}
|
||||
topView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_screen_lock, null);
|
||||
initTopView(topView, name);
|
||||
// topView.setAlpha(0.8f);
|
||||
// 设置LayoutParam
|
||||
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
layoutParams.type = WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
|
||||
//TYPE_SYSTEM_OVERLAY可以下滑通知栏
|
||||
// layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
|
||||
} else {
|
||||
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
|
||||
}
|
||||
layoutParams.flags |= WindowManager.LayoutParams.FLAG_BLUR_BEHIND
|
||||
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
|
||||
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
|
||||
layoutParams.format = PixelFormat.RGBA_8888;
|
||||
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
|
||||
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
|
||||
//systemUiVisibility 关闭通知栏和导航栏
|
||||
layoutParams.systemUiVisibility =
|
||||
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
| View.SYSTEM_UI_FLAG_IMMERSIVE
|
||||
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
|
||||
layoutParams.x = 0;
|
||||
layoutParams.y = 0;
|
||||
// 将悬浮窗控件添加到WindowManager
|
||||
} else {
|
||||
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
|
||||
}
|
||||
layoutParams.flags |= WindowManager.LayoutParams.FLAG_BLUR_BEHIND
|
||||
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
|
||||
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
|
||||
layoutParams.format = PixelFormat.RGBA_8888;
|
||||
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
|
||||
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
|
||||
//systemUiVisibility 关闭通知栏和导航栏
|
||||
layoutParams.systemUiVisibility =
|
||||
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
| View.SYSTEM_UI_FLAG_IMMERSIVE
|
||||
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
|
||||
layoutParams.x = 0;
|
||||
layoutParams.y = 0;
|
||||
// 将悬浮窗控件添加到WindowManager
|
||||
try {
|
||||
windowManager.addView(topView, layoutParams);
|
||||
topView.setTag("added");
|
||||
Log.e(TAG, "showFloatingWindow: added. name=" + name);
|
||||
} catch (Exception e) {
|
||||
// 添加失败时不能留下脏引用,否则下一分钟 tick 会一直复用它
|
||||
Log.e(TAG, "showFloatingWindow: addView failed: " + e.getMessage());
|
||||
topView = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,11 +372,6 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
|
||||
private void hide() {
|
||||
hideFloatingWindow();
|
||||
// 视图已移除,内存状态必须同步复位:
|
||||
// 否则下一次 setFloatingWindow() 会走到 screenlocked==true 分支去访问已置空的 topView,
|
||||
// 抛出 NPE(release 包被全局异常捕获吞掉),表现为锁屏浮窗再也不出现。
|
||||
screenlocked = false;
|
||||
timelocked = false;
|
||||
// 密码解锁改用内存标记表达,不再在这里把 LOCK_STATE 直接清 0;
|
||||
// 该 key 交给"按服务端状态落地"的路径(setLockedState / 推送 / 轮询)统一维护。
|
||||
pwdUnlocked = true;
|
||||
@@ -413,11 +407,28 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
}
|
||||
|
||||
private void hideFloatingWindow() {
|
||||
if (null == windowManager) {
|
||||
removeTopViewSafely();
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全移除锁屏浮窗。
|
||||
* removeView 在"View 已被系统移除"时会抛 IllegalArgumentException,
|
||||
* 这里用 try/catch 兜住,并在 finally 里把 topView 置空,
|
||||
* 否则会留下脏引用,后续再也弹不出锁屏。
|
||||
* 注意:不能用 isAttachedToWindow() 做前置判断 —— addView 之后、第一次 traversal 之前
|
||||
* 它仍为 false,会漏掉真正的 removeView,导致浮窗泄漏且永远关不掉。
|
||||
*/
|
||||
private void removeTopViewSafely() {
|
||||
if (null == topView) {
|
||||
return;
|
||||
}
|
||||
if (null != topView) {
|
||||
windowManager.removeView(topView);
|
||||
try {
|
||||
if (null != windowManager) {
|
||||
windowManager.removeView(topView);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "removeTopViewSafely: " + e.getMessage());
|
||||
} finally {
|
||||
topView = null;
|
||||
}
|
||||
}
|
||||
@@ -449,17 +460,11 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
String name = "屏幕已锁定";
|
||||
// 服务端状态已下发,本地"密码解锁"标记失效
|
||||
pwdUnlocked = false;
|
||||
if (!timelocked) {
|
||||
showFloatingWindow(name);
|
||||
}
|
||||
screenlocked = true;
|
||||
showFloatingWindow(name);
|
||||
} else if (ACTION_UNLOCK.equals(action)) {
|
||||
// 服务端状态已下发,本地"密码解锁"标记失效
|
||||
pwdUnlocked = false;
|
||||
if (!timelocked) {
|
||||
hideFloatingWindow();
|
||||
}
|
||||
screenlocked = false;
|
||||
hideFloatingWindow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -467,7 +472,7 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
private TimeChangedReceiver mTimeChangedReceiver;
|
||||
|
||||
/**
|
||||
* 监听时间和日期变化
|
||||
* 监听时间和日期变化,作为锁屏状态丢失(推送未到、进程被回收)时的兜底刷新
|
||||
*/
|
||||
private void registerTimeReceiver() {
|
||||
mTimeChangedReceiver = new TimeChangedReceiver();
|
||||
@@ -477,7 +482,6 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
filter.addAction(Intent.ACTION_TIME_CHANGED);
|
||||
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
|
||||
filter.addAction(Intent.ACTION_TIME_TICK);
|
||||
filter.addAction(ACTION_UPDATE);
|
||||
registerReceiver(mTimeChangedReceiver, filter);
|
||||
}
|
||||
|
||||
@@ -487,8 +491,7 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
String action = intent.getAction();
|
||||
if (Intent.ACTION_DATE_CHANGED.equals(action)) {
|
||||
Log.e(TAG, "TimeChangedReceiver:" + "data changed");
|
||||
// 跨天后"工作日/周末"规则集会切换,立即按新日期重算,
|
||||
// 避免浮窗/锁屏状态延迟到下一次 TIME_TICK 才生效
|
||||
// 跨天后立即按服务端锁屏状态重算一次
|
||||
setFloatingWindow();
|
||||
} else if (Intent.ACTION_TIME_CHANGED.equals(action)) {
|
||||
Log.e(TAG, "TimeChangedReceiver:" + "time changed");
|
||||
@@ -497,9 +500,6 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
} else if (Intent.ACTION_TIME_TICK.equals(action)) {
|
||||
Log.e(TAG, "TimeChangedReceiver:" + "time tick");
|
||||
setFloatingWindow();
|
||||
} else if (ACTION_UPDATE.equals(action)) {
|
||||
Log.e(TAG, "TimeChangedReceiver:" + "date update");
|
||||
setFloatingWindow();
|
||||
}
|
||||
|
||||
|
||||
@@ -511,42 +511,15 @@ public class ManagerService extends Service implements NetworkUtils.OnNetworkSta
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按服务端锁屏状态刷新锁屏浮窗(唯一的锁屏来源)。
|
||||
* 由 TIME_TICK / DATE_CHANGED 周期驱动,用于兜底:
|
||||
* 推送丢失、进程被回收重启后,只要 SP 里还留着 LOCK_STATE 就能自动恢复锁屏。
|
||||
*/
|
||||
private void setFloatingWindow() {
|
||||
TimeUtils.ContralTime workingContralTime = TimeUtils.getWorkingDayContralTime(ManagerService.this);
|
||||
TimeUtils.ContralTime weekContralTime = TimeUtils.getWeekDayContralTime(ManagerService.this);
|
||||
// if (null != workingContralTime) {
|
||||
// 先算出本轮的时间管控状态并落到 timelocked,再处理 UI/锁屏状态:
|
||||
// setLockedState() 与 LockScreenReceiver 内部都要判断 timelocked,
|
||||
// 若在调用之后才赋值,会出现"服务端锁屏已下发但不显示"的空窗(最长到下一次 TIME_TICK)。
|
||||
boolean inTimeControl = TimeUtils.inContralTime(workingContralTime, weekContralTime);
|
||||
timelocked = inTimeControl;
|
||||
String timeText = "可用时间:\n" + TimeUtils.getNowTimeString(ManagerService.this);
|
||||
if (inTimeControl) {
|
||||
if (null == topView) {
|
||||
// topView 可能已被 hideFloatingWindow()(密码解锁、解锁广播)移除,
|
||||
// 此时不能再对 topView 取子控件,否则 NPE 会导致浮窗再也不显示。
|
||||
showFloatingWindow(timeText);
|
||||
} else {
|
||||
TextView textView = topView.findViewById(R.id.textView);
|
||||
if (null != textView) {
|
||||
textView.setText(timeText);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// getScreenLockState();
|
||||
int is_screen_lock = getServerLockState();
|
||||
setLockedState(is_screen_lock);
|
||||
if (!screenlocked) {
|
||||
hideFloatingWindow();
|
||||
}
|
||||
}
|
||||
// } else {
|
||||
// if (!screenlocked) {
|
||||
// hideFloatingWindow()
|
||||
// }
|
||||
// getScreenLockState()
|
||||
// timelocked = false
|
||||
// }
|
||||
// 需要以服务端为准时,可改成先 getScreenLockState() 拉一次再落地
|
||||
int is_screen_lock = getServerLockState();
|
||||
setLockedState(is_screen_lock);
|
||||
}
|
||||
|
||||
private ScreenLockReceiver screenLockReceiver;
|
||||
|
||||
@@ -63,6 +63,32 @@ import io.reactivex.rxjava3.disposables.Disposable;
|
||||
public class MainService extends LifecycleService implements ViewModelStoreOwner, NetworkUtils.OnNetworkStatusChangedListener {
|
||||
private static final String TAG = "MainService";
|
||||
|
||||
/**
|
||||
* 启动/重启后首次拉取配置的基础延时(毫秒)
|
||||
*/
|
||||
private static final long STARTUP_DELAY_BASE = 20 * 1000L;
|
||||
|
||||
/**
|
||||
* 网络重连后首次拉取配置的基础延时(毫秒)
|
||||
*/
|
||||
private static final long STARTUP_DELAY_NETWORK = 15 * 1000L;
|
||||
|
||||
/**
|
||||
* 启动后首次请求的随机错峰上限(毫秒)。
|
||||
* <p>
|
||||
* 静默升级是全量下发的:整批设备几乎同时下载、同时安装、同时重启,
|
||||
* 若重启后都在固定时刻集中请求接口,服务端会被瞬时打挂。
|
||||
* 因此在基础延时上再叠加一段随机时间,把整批设备的请求摊开到 10 分钟内。
|
||||
*/
|
||||
private static final long STARTUP_DELAY_SPREAD = 10 * 60 * 1000L;
|
||||
|
||||
/**
|
||||
* 计算首次拉取接口的错峰延时:基础延时 + [0, {@link #STARTUP_DELAY_SPREAD}) 随机值
|
||||
*/
|
||||
private static long nextStartupDelay(long baseDelay) {
|
||||
return TimeUtils.randomDelay(baseDelay, baseDelay + STARTUP_DELAY_SPREAD);
|
||||
}
|
||||
|
||||
private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
|
||||
|
||||
private MainServiceModel mViewModel;
|
||||
@@ -89,7 +115,8 @@ public class MainService extends LifecycleService implements ViewModelStoreOwner
|
||||
// if (reboot) {
|
||||
//第一次开机联网后直接连接
|
||||
// TODO: 2022/11/21 有些设备联网了但是立刻请求还是失败
|
||||
Log.e(TAG, "onConnected run: 15秒后请求网络");
|
||||
long connectedDelay = nextStartupDelay(STARTUP_DELAY_NETWORK);
|
||||
Log.e(TAG, "onConnected run: " + (connectedDelay / 1000) + "秒后请求网络");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -108,7 +135,7 @@ public class MainService extends LifecycleService implements ViewModelStoreOwner
|
||||
SPUtils.put(MainService.this, CommonConfig.JGY_FIRST_BOOT, 1);
|
||||
}
|
||||
}
|
||||
}, 15000);
|
||||
}, connectedDelay);
|
||||
mMMKV.encode(CommonConfig.DEVICES_REBOOT, false);
|
||||
// }
|
||||
// NetInterfaceManager.getInstance().updateAdminInfo();
|
||||
@@ -176,7 +203,9 @@ public class MainService extends LifecycleService implements ViewModelStoreOwner
|
||||
boolean networkConnected = JgyUtils.getInstance().isNetworkConnected();
|
||||
Log.e(TAG, "onCreate: networkConnected = " + networkConnected);
|
||||
// if (networkConnected && reboot) {
|
||||
Log.e(TAG, "onCreate run: 20秒后请求网络");
|
||||
//升级重启后所有设备都在这里发起首批请求,加随机错峰避免集中打挂服务端
|
||||
long startupDelay = nextStartupDelay(STARTUP_DELAY_BASE);
|
||||
Log.e(TAG, "onCreate run: " + (startupDelay / 1000) + "秒后请求网络");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -191,7 +220,7 @@ public class MainService extends LifecycleService implements ViewModelStoreOwner
|
||||
NetInterfaceManager.getInstance().SendAppInstallInfo();
|
||||
}
|
||||
}
|
||||
}, 20000);
|
||||
}, startupDelay);
|
||||
mMMKV.encode(CommonConfig.DEVICES_REBOOT, false);
|
||||
// } else {
|
||||
// NetInterfaceManager.getInstance().updateAdminInfo();
|
||||
|
||||
@@ -161,6 +161,7 @@ public class JgyUtils {
|
||||
this.add("com.fuying.middle.english");
|
||||
this.add("com.qijuqiyi");
|
||||
this.add("com.fuyingedu.fylxy_test");
|
||||
this.add("com.fuying.work");
|
||||
}};
|
||||
|
||||
public static final String fxyywgj = "com.fuying.chinese";
|
||||
|
||||
@@ -1,60 +1,31 @@
|
||||
package com.fuying.sn.utils;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.SystemClock;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
import com.fuying.sn.bean.PartTime;
|
||||
import com.fuying.sn.data.model.AppControlDetail;
|
||||
import com.fuying.sn.service.ManagerService;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class TimeUtils {
|
||||
private static final String TAG = "TimeUtils";
|
||||
private static DateFormat df = new SimpleDateFormat("HH:mm");
|
||||
public static final String START_TIME_KEY = "START_TIME";
|
||||
public static final String END_TIME_KEY = "END_TIME";
|
||||
public static final String WEEK_START_TIME_KEY = "WEEK_START_TIME";
|
||||
public static final String WEEK_END_TIME_KEY = "WEEK_END_TIME";
|
||||
public static long dayTime = 60 * 60 * 24 * 1000;
|
||||
public static long minuteTime = 60 * 1000;
|
||||
|
||||
|
||||
public static String getNowTime() {
|
||||
long nowTime = System.currentTimeMillis();
|
||||
DateFormat df = ContralTime.getDf();
|
||||
return df.format(nowTime);
|
||||
}
|
||||
|
||||
// public static boolean CurrentInTimeScope(ContralTime contralTime) {
|
||||
// boolean result = true;
|
||||
// final long aDayInMillis = 1000 * 60 * 60 * 24;
|
||||
// long currentTimeMillis = System.currentTimeMillis();
|
||||
//
|
||||
// }
|
||||
|
||||
public static String transferLongToDate(Long millSec) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
@@ -72,129 +43,6 @@ public class TimeUtils {
|
||||
return localTime.isAfter(startTime) && localTime.isBefore(endTime);
|
||||
}
|
||||
|
||||
public static ContralTime String2WorkingTime(Context context, @NonNull String timeText) {
|
||||
DateFormat df = ContralTime.getDf();
|
||||
String[] time = timeText.trim().split("-");
|
||||
if (time.length != 2) {
|
||||
// return null;
|
||||
throw new RuntimeException("Time format error!" + Arrays.toString(time));
|
||||
}
|
||||
try {
|
||||
SPUtils.put(context, START_TIME_KEY, time[0].trim());
|
||||
SPUtils.put(context, END_TIME_KEY, time[1].trim());
|
||||
Date startDate = df.parse(time[0].trim());
|
||||
Date endDate = df.parse(time[1].trim());
|
||||
ContralTime contralTime = new ContralTime();
|
||||
// if (date1.getTime() < date2.getTime()) {
|
||||
contralTime.setStartTime(df.format(startDate));
|
||||
contralTime.setEndTime(df.format(endDate));
|
||||
// } else {
|
||||
// contralTime.setStartTime(df.format(date2));
|
||||
// contralTime.setEndTime(df.format(date1));
|
||||
// }
|
||||
return contralTime;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static ContralTime String2WeekTime(Context context, @NonNull String timeText) {
|
||||
DateFormat df = ContralTime.getDf();
|
||||
String[] time = timeText.trim().split("-");
|
||||
if (time.length != 2) {
|
||||
// return null;
|
||||
throw new RuntimeException("Time format error!" + Arrays.toString(time));
|
||||
}
|
||||
try {
|
||||
SPUtils.put(context, WEEK_START_TIME_KEY, time[0].trim());
|
||||
SPUtils.put(context, WEEK_END_TIME_KEY, time[1].trim());
|
||||
Date startDate = df.parse(time[0].trim());
|
||||
Date endDate = df.parse(time[1].trim());
|
||||
ContralTime contralTime = new ContralTime();
|
||||
// if (date1.getTime() < date2.getTime()) {
|
||||
contralTime.setStartTime(df.format(startDate));
|
||||
contralTime.setEndTime(df.format(endDate));
|
||||
// } else {
|
||||
// contralTime.setStartTime(df.format(date2));
|
||||
// contralTime.setEndTime(df.format(date1));
|
||||
// }
|
||||
return contralTime;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static ContralTime getWorkingDayContralTime(Context context) {
|
||||
String startTime = (String) SPUtils.get(context, START_TIME_KEY, "00:00");
|
||||
String endTime = (String) SPUtils.get(context, END_TIME_KEY, "00:00");
|
||||
return getContralTime(context, startTime, endTime);
|
||||
}
|
||||
|
||||
public static ContralTime getWeekDayContralTime(Context context) {
|
||||
String startTime = (String) SPUtils.get(context, WEEK_START_TIME_KEY, "00:00");
|
||||
String endTime = (String) SPUtils.get(context, WEEK_END_TIME_KEY, "00:00");
|
||||
return getContralTime(context, startTime, endTime);
|
||||
}
|
||||
|
||||
public static boolean inContralTime(ContralTime workingTime, ContralTime weekTime) {
|
||||
if (inWeekDay()) {
|
||||
if (weekTime == null) {
|
||||
return false;
|
||||
} else {
|
||||
return weekTime.inControlTime();
|
||||
}
|
||||
} else {
|
||||
if (workingTime == null) {
|
||||
return false;
|
||||
} else {
|
||||
return workingTime.inControlTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static ContralTime getContralTime(Context context, String startTime, String endTime) {
|
||||
if (null == startTime || null == endTime || ("00:00".equals(startTime) && "00:00".equals(endTime))) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
Date startDate = df.parse(startTime.trim());
|
||||
Date endDate = df.parse(endTime.trim());
|
||||
ContralTime contralTime = new ContralTime();
|
||||
contralTime.setStartTime(df.format(startDate));
|
||||
contralTime.setEndTime(df.format(endDate));
|
||||
return contralTime;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNowTimeString(Context context) {
|
||||
ContralTime work = getWorkingDayContralTime(context);
|
||||
ContralTime week = getWeekDayContralTime(context);
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
if (work != null) {
|
||||
stringBuilder.append("周一至周五:").append(work).append("\n");
|
||||
}
|
||||
if (week != null) {
|
||||
stringBuilder.append("周末:").append(week);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
public static void setEmpty(Context context) {
|
||||
SPUtils.put(context, START_TIME_KEY, "00:00");
|
||||
SPUtils.put(context, END_TIME_KEY, "00:00");
|
||||
SPUtils.put(context, WEEK_START_TIME_KEY, "00:00");
|
||||
SPUtils.put(context, WEEK_END_TIME_KEY, "00:00");
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(ManagerService.ACTION_UPDATE);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取格式化后的时间
|
||||
*
|
||||
@@ -339,90 +187,6 @@ public class TimeUtils {
|
||||
SystemClock.setCurrentTimeMillis(time);
|
||||
}
|
||||
|
||||
public static class ContralTime {
|
||||
//format HH:mm
|
||||
String startTime;
|
||||
String endTime;
|
||||
|
||||
public ContralTime() {
|
||||
|
||||
}
|
||||
|
||||
public ContralTime(String startT, String endT) {
|
||||
this.startTime = startT;
|
||||
this.endTime = endT;
|
||||
}
|
||||
|
||||
public String getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
|
||||
public void setStartTime(String startT) {
|
||||
this.startTime = startT;
|
||||
}
|
||||
|
||||
public String getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(String endT) {
|
||||
this.endTime = endT;
|
||||
}
|
||||
|
||||
public static DateFormat getDf() {
|
||||
return df;
|
||||
}
|
||||
|
||||
public static void setDf(DateFormat d) {
|
||||
df = d;
|
||||
}
|
||||
|
||||
public String getNowTimeString(long time) {
|
||||
return df.format(new Date(time));
|
||||
}
|
||||
|
||||
public boolean inControlTime() {
|
||||
long time = System.currentTimeMillis();
|
||||
return inControlTime(time);
|
||||
}
|
||||
|
||||
public boolean inControlTime(long time) {
|
||||
return inControlTime(df.format(new Date(time)));
|
||||
}
|
||||
|
||||
public boolean inControlTime(String time) {
|
||||
if (TextUtils.isEmpty(time)) {
|
||||
throw new RuntimeException("Time is empty");
|
||||
} else {
|
||||
if (!time.contains(":")) {
|
||||
throw new RuntimeException("Time format error");
|
||||
}
|
||||
}
|
||||
try {
|
||||
Date startDate = df.parse(startTime);
|
||||
Date endDate = df.parse(endTime);
|
||||
Date nowDate = df.parse(time);
|
||||
if (startDate.getTime() > endDate.getTime()) {
|
||||
//开始时间大于结束时间 列 16:00-01:00
|
||||
endDate.setTime(endDate.getTime() + dayTime);
|
||||
}
|
||||
Log.e(TAG, "inControlTime: " + (startDate.getTime() - minuteTime));
|
||||
assert nowDate != null;
|
||||
return nowDate.getTime() <= startDate.getTime() - minuteTime || nowDate.getTime() >= endDate.getTime();
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return startTime + "\t-\t" + endTime;
|
||||
}
|
||||
}
|
||||
|
||||
private static SntpClient mNtpClient;
|
||||
|
||||
public static long getTimeFromNtpServer(String hostAddress) {
|
||||
@@ -656,4 +420,96 @@ public class TimeUtils {
|
||||
return today.equals(dateToCheck);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 夜间窗口 & 多设备错峰
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* 静默升级窗口起始小时(含)。
|
||||
* 项目约定:推送与静默升级只在 23:00 ~ 次日 05:00 之间进行。
|
||||
*/
|
||||
public static final int NIGHT_WINDOW_START_HOUR = 23;
|
||||
|
||||
/**
|
||||
* 静默升级窗口结束小时(不含)。窗口跨天:[23:00, 24:00) ∪ [00:00, 05:00)。
|
||||
*/
|
||||
public static final int NIGHT_WINDOW_END_HOUR = 5;
|
||||
|
||||
/**
|
||||
* 当前时间是否处于静默升级窗口(23:00 ~ 次日 05:00)
|
||||
*/
|
||||
public static boolean isInNightWindow() {
|
||||
return isInNightWindow(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定时间戳是否处于静默升级窗口(23:00 ~ 次日 05:00)
|
||||
*/
|
||||
public static boolean isInNightWindow(long time) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis(time);
|
||||
int hour = calendar.get(Calendar.HOUR_OF_DAY);
|
||||
return hour >= NIGHT_WINDOW_START_HOUR || hour < NIGHT_WINDOW_END_HOUR;
|
||||
}
|
||||
|
||||
/**
|
||||
* 距离当前窗口结束还剩多少毫秒;不在窗口内返回 0。
|
||||
*/
|
||||
public static long millisToNightWindowEnd() {
|
||||
long now = System.currentTimeMillis();
|
||||
if (!isInNightWindow(now)) {
|
||||
return 0;
|
||||
}
|
||||
Calendar target = Calendar.getInstance();
|
||||
target.setTimeInMillis(now);
|
||||
if (target.get(Calendar.HOUR_OF_DAY) < NIGHT_WINDOW_END_HOUR) {
|
||||
// 00:00 ~ 05:00,窗口结束在当天 05:00
|
||||
target.set(Calendar.HOUR_OF_DAY, NIGHT_WINDOW_END_HOUR);
|
||||
} else {
|
||||
// 23:00 ~ 24:00,窗口结束在次日 05:00
|
||||
target.add(Calendar.DAY_OF_YEAR, 1);
|
||||
target.set(Calendar.HOUR_OF_DAY, NIGHT_WINDOW_END_HOUR);
|
||||
}
|
||||
target.set(Calendar.MINUTE, 0);
|
||||
target.set(Calendar.SECOND, 0);
|
||||
target.set(Calendar.MILLISECOND, 0);
|
||||
return target.getTimeInMillis() - now;
|
||||
}
|
||||
|
||||
/**
|
||||
* 距离下一次进入窗口还剩多少毫秒;已在窗口内返回 0。
|
||||
*/
|
||||
public static long millisToNextNightWindow() {
|
||||
long now = System.currentTimeMillis();
|
||||
if (isInNightWindow(now)) {
|
||||
return 0;
|
||||
}
|
||||
Calendar target = Calendar.getInstance();
|
||||
target.setTimeInMillis(now);
|
||||
// 不在窗口内时(05:00 ~ 23:00),今天 23:00 一定在未来
|
||||
target.set(Calendar.HOUR_OF_DAY, NIGHT_WINDOW_START_HOUR);
|
||||
target.set(Calendar.MINUTE, 0);
|
||||
target.set(Calendar.SECOND, 0);
|
||||
target.set(Calendar.MILLISECOND, 0);
|
||||
if (target.getTimeInMillis() <= now) {
|
||||
target.add(Calendar.DAY_OF_YEAR, 1);
|
||||
}
|
||||
return target.getTimeInMillis() - now;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 [minMillis, maxMillis) 区间内的随机延时。
|
||||
* 用于多设备错峰:静默升级是全量下发,若所有设备在同一时刻下载/请求,
|
||||
* 会把服务端打挂,这里用随机延时把请求摊开。
|
||||
*
|
||||
* @param minMillis 最小延时(含)
|
||||
* @param maxMillis 最大延时(不含)
|
||||
*/
|
||||
public static long randomDelay(long minMillis, long maxMillis) {
|
||||
if (maxMillis <= minMillis) {
|
||||
return Math.max(minMillis, 0);
|
||||
}
|
||||
return minMillis + (long) (Math.random() * (maxMillis - minMillis));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user