refactor(app): 统一工具类并简化服务架构
- 移除 GuardService、StepService、ControlPanelService,替换为 SocketService - 将 QR 码生成从 Utils 迁移到 BitmapUtils - 将缓存目录选择逻辑统一到 FileUtils.getCacheFileDir - 将 ServiceAliveUtils、NetStateUtils 合并到 SystemUtils - 将 CacheUtils 同步清理替换为 ApkUtils.cleanApplicationUserDataAsync - 用 EncryptUtils 替代自定义 MD5Util - 重写 catchException 支持主线程兜底循环与子线程 Bugly 上报 - 移除 RunningAppManager 中未使用的 killBackgroundProcesses 方法 - 移除 ControlManager 中冗余的 hideSystemSettingAPP 调用 - MyGlideModule 重命名为 BaseGlideModule
This commit is contained in:
1 parent
df8a7bc153
commit
a972ce7b89
46 files changed
+1583
-1812
No files matched your search
@@ -1,104 +0,0 @@
|
||||
package com.fuying.sn.service;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.hardware.usb.UsbPortStatus;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
|
||||
public class ControlPanelService extends Service {
|
||||
private static final String TAG = "ControlPanelService";
|
||||
|
||||
public ControlPanelService() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
registerUsbConnectionReceiver();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
return super.onStartCommand(intent, flags, startId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void registerUsbConnectionReceiver() {
|
||||
if (mUsbConnectionReceiver == null) {
|
||||
mUsbConnectionReceiver = new UsbConnectionReceiver();
|
||||
}
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(UsbManager.ACTION_USB_STATE);
|
||||
filter.addAction(UsbManager.ACTION_USB_PORT_CHANGED);
|
||||
registerReceiver(mUsbConnectionReceiver, filter);
|
||||
}
|
||||
|
||||
UsbConnectionReceiver mUsbConnectionReceiver;
|
||||
|
||||
private boolean mConnected;
|
||||
private long mFunctions;
|
||||
// private int mDataRole;
|
||||
// private int mPowerRole;
|
||||
|
||||
public class UsbConnectionReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
Log.e(TAG, "onReceive: " + intent.getAction());
|
||||
Bundle bundle = intent.getExtras();
|
||||
if (UsbManager.ACTION_USB_STATE.equals(intent.getAction())) {
|
||||
mConnected = intent.getExtras().getBoolean(UsbManager.USB_CONNECTED)
|
||||
|| intent.getExtras().getBoolean(UsbManager.USB_HOST_CONNECTED);
|
||||
long functions = UsbManager.FUNCTION_NONE;
|
||||
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_MTP)
|
||||
&& intent.getExtras().getBoolean(UsbManager.USB_DATA_UNLOCKED, false)) {
|
||||
functions |= UsbManager.FUNCTION_MTP;
|
||||
}
|
||||
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_PTP)
|
||||
&& intent.getExtras().getBoolean(UsbManager.USB_DATA_UNLOCKED, false)) {
|
||||
functions |= UsbManager.FUNCTION_PTP;
|
||||
}
|
||||
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_MIDI)) {
|
||||
functions |= UsbManager.FUNCTION_MIDI;
|
||||
}
|
||||
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_RNDIS)) {
|
||||
functions |= UsbManager.FUNCTION_RNDIS;
|
||||
}
|
||||
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_ACCESSORY)) {
|
||||
functions |= UsbManager.FUNCTION_ACCESSORY;
|
||||
}
|
||||
mFunctions = functions;
|
||||
|
||||
// mDataRole = mUsbBackend.getDataRole();
|
||||
// mPowerRole = mUsbBackend.getPowerRole();
|
||||
} else if (UsbManager.ACTION_USB_PORT_CHANGED.equals(intent.getAction())) {
|
||||
UsbPortStatus portStatus = intent.getExtras()
|
||||
.getParcelable(UsbManager.EXTRA_PORT_STATUS);
|
||||
if (portStatus != null) {
|
||||
// mDataRole = portStatus.getCurrentDataRole();
|
||||
// mPowerRole = portStatus.getCurrentPowerRole();
|
||||
}
|
||||
}
|
||||
// if (mUsbConnectionListener != null) {
|
||||
// mUsbConnectionListener.onUsbConnectionChanged(mConnected, mFunctions, mPowerRole,
|
||||
// mDataRole);
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.fuying.sn.service;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.app.Service;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
@@ -41,11 +40,10 @@ public class DownloadService extends BaseService {
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
startService(new Intent(this, StepService.class));
|
||||
startService(new Intent(this, GuardService.class));
|
||||
super.onStartCommand(intent, flags, startId);
|
||||
startService(new Intent(this, SocketService.class));
|
||||
startService(new Intent(this, MainService.class));
|
||||
startService(new Intent(this, ManagerService.class));
|
||||
startService(new Intent(this, ControlPanelService.class));
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@@ -59,6 +57,7 @@ public class DownloadService extends BaseService {
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
super.onBind(intent);
|
||||
return new KeepAliveConnection.Stub() {
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.fuying.sn.service;
|
||||
|
||||
/**
|
||||
* 作者 mjsheng
|
||||
* 日期 2019/4/1 10:58
|
||||
* 邮箱 501802639@qq.com
|
||||
* 来自:
|
||||
*/
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.fuying.sn.KeepAliveConnection;
|
||||
import com.fuying.sn.utils.ServiceAliveUtils;
|
||||
|
||||
|
||||
/**
|
||||
* 守护进程 双进程通讯
|
||||
*
|
||||
* @author LiGuangMin
|
||||
* @time Created by 2018/8/17 11:27
|
||||
*/
|
||||
public class GuardService extends Service {
|
||||
private static final String TAG = "GuardService";
|
||||
private ServiceConnection mServiceConnection = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
|
||||
Log.e(TAG, "GuardService:建立链接");
|
||||
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(GuardService.this, getClass().getName());
|
||||
if (!isServiceRunning) {
|
||||
Intent i = new Intent(GuardService.this, DownloadService.class);
|
||||
startService(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName componentName) {
|
||||
// 断开链接
|
||||
startService(new Intent(GuardService.this, StepService.class));
|
||||
// 重新绑定
|
||||
bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return new KeepAliveConnection.Stub() {
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
// 绑定建立链接
|
||||
bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||||
return START_STICKY;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,11 +45,13 @@ public class LogcatService extends BaseService {
|
||||
public IBinder onBind(Intent intent) {
|
||||
// TODO: 如需支持绑定服务,在此返回通信接口;当前仅通过启动服务和广播控制。
|
||||
// throw new UnsupportedOperationException("Not yet implemented");
|
||||
super.onBind(intent);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
super.onStartCommand(intent, flags, startId);
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
|
||||
@Override
|
||||
public void onConnected(NetworkUtils.NetworkType networkType) {
|
||||
// getScreenLockState();
|
||||
// 网络恢复后立即兜底刷新一次配置(推送可能在此期间丢失)
|
||||
try {
|
||||
PushManager.getInstance().triggerRefresh();
|
||||
@@ -128,6 +127,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
super.onBind(intent);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -137,10 +137,8 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
NetworkUtils.registerNetworkStatusChangedListener(this);
|
||||
registLockReceiver();
|
||||
registerTimeReceiver();
|
||||
registerScreenLockReceiver();
|
||||
registAppReceive();
|
||||
registBootReceive();
|
||||
registerBatteryReceiver();
|
||||
setFloatingWindow();
|
||||
Observable.create(subscribe)
|
||||
.throttleFirst(3, TimeUnit.HOURS)
|
||||
@@ -149,6 +147,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
super.onStartCommand(intent, flags, startId);
|
||||
start.onstar(System.currentTimeMillis());
|
||||
return START_STICKY;
|
||||
}
|
||||
@@ -490,13 +489,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
Log.e(TAG, "TimeChangedReceiver:" + "time tick");
|
||||
setFloatingWindow();
|
||||
}
|
||||
|
||||
|
||||
// String packages = ForegroundAppUtil.getForegroundPackageName(context);
|
||||
// if (!packages.equals("com.estrongs.android.pop")) {
|
||||
// ApkUtils.openApp(context, "com.estrongs.android.pop");
|
||||
// }
|
||||
// Log.e("TimeChangedReceiver", "packages:" + packages);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -511,50 +503,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
setLockedState(is_screen_lock);
|
||||
}
|
||||
|
||||
private ScreenLockReceiver screenLockReceiver;
|
||||
|
||||
private void registerScreenLockReceiver() {
|
||||
if (null == screenLockReceiver) {
|
||||
screenLockReceiver = new ScreenLockReceiver();
|
||||
}
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
|
||||
filter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
filter.addAction(Intent.ACTION_SCREEN_ON);
|
||||
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
|
||||
filter.addAction(Intent.ACTION_USER_PRESENT);
|
||||
filter.addAction(Intent.ACTION_SHUTDOWN);
|
||||
filter.addAction(Intent.ACTION_FACTORY_RESET);
|
||||
filter.addAction(Intent.ACTION_MASTER_CLEAR);
|
||||
registerReceiver(screenLockReceiver, filter);
|
||||
}
|
||||
|
||||
private class ScreenLockReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
Log.e(TAG, "onReceive:" + action);
|
||||
if (TextUtils.isEmpty(action)) {
|
||||
Log.e(TAG, "onReceive: is NULL");
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
case Intent.ACTION_USER_PRESENT:
|
||||
case Intent.ACTION_SCREEN_ON:
|
||||
// sendScreenState(1);
|
||||
break;
|
||||
case Intent.ACTION_SCREEN_OFF:
|
||||
case Intent.ACTION_SHUTDOWN:
|
||||
case Intent.ACTION_FACTORY_RESET:
|
||||
case Intent.ACTION_MASTER_CLEAR:
|
||||
// sendScreenState(0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ApkInstallReceiver apKinstallReceiver;
|
||||
|
||||
private void registAppReceive() {
|
||||
@@ -582,33 +530,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
}
|
||||
}
|
||||
|
||||
private BatteryReceiver batteryReceiver;
|
||||
|
||||
private void registerBatteryReceiver() {
|
||||
if (null == batteryReceiver) {
|
||||
batteryReceiver = new BatteryReceiver();
|
||||
}
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
|
||||
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
|
||||
registerReceiver(batteryReceiver, filter);
|
||||
}
|
||||
|
||||
private class BatteryReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
|
||||
|
||||
} else if (Intent.ACTION_POWER_CONNECTED.equals(action) || Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
|
||||
// ControlManager.getInstance().setDefaultUSBstate();
|
||||
} else if (Intent.ACTION_BATTERY_LOW.equals(action) || Intent.ACTION_BATTERY_OKAY.equals(action)) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
mDisposables.dispose();
|
||||
@@ -620,9 +541,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
|
||||
if (null != lockScreenReceiver) {
|
||||
unregisterReceiver(lockScreenReceiver);
|
||||
}
|
||||
if (null != screenLockReceiver) {
|
||||
unregisterReceiver(screenLockReceiver);
|
||||
}
|
||||
if (null != apKinstallReceiver) {
|
||||
unregisterReceiver(apKinstallReceiver);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
package com.fuying.sn.service;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.IBinder;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.lifecycle.Lifecycle;
|
||||
import androidx.lifecycle.LifecycleEventObserver;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LifecycleService;
|
||||
|
||||
import com.blankj.utilcode.util.NetworkUtils;
|
||||
import com.fuying.sn.utils.ReceiverCompat;
|
||||
import com.fuying.sn.utils.SystemUtils;
|
||||
import com.fuying.sn.utils.TimeUtils;
|
||||
import com.fuying.sn.utils.Utils;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import io.reactivex.rxjava3.core.Single;
|
||||
import io.reactivex.rxjava3.disposables.CompositeDisposable;
|
||||
import io.reactivex.rxjava3.disposables.SerialDisposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.WebSocket;
|
||||
import okhttp3.WebSocketListener;
|
||||
|
||||
/**
|
||||
* 设备 WebSocket 长连接服务:用 OkHttp 建立连接,用 RxJava 驱动心跳、重连与错峰。
|
||||
*
|
||||
* <p>继承 {@link LifecycleService} 后,所有资源(订阅、广播、网络监听、WebSocket)都在
|
||||
* Lifecycle 的 ON_CREATE 中创建、ON_DESTROY 中释放;流里还会检查 Lifecycle 状态,
|
||||
* DESTROYED 之后不再有任何连接动作。不再依赖 Service 自身回调去手动管理生命周期。
|
||||
*
|
||||
* <p>连接状态(mConnecting / mOpened / mWebSocket)只在主线程读写:OkHttp 回调和网络
|
||||
* 状态回调都先切回主线程,心跳流和错峰任务也通过 observeOn 回到主线程。这样建连、
|
||||
* 关闭、失败回调天然串行,不会出现两个线程同时建连或状态互相覆盖。
|
||||
*
|
||||
* <p>连接时机沿用屏幕状态策略:亮屏广播触发重连,息屏广播主动断开并取消在途任务,
|
||||
* 息屏后心跳流停止,不再重连。
|
||||
*
|
||||
* <p>这里不做进程保活:双进程 AIDL 互拉(GuardService / KeepAliveConnection)已移除,
|
||||
* 服务只由 BaseApplication、BootReceiver、MainService 等入口显式启动。
|
||||
*/
|
||||
public class SocketService extends LifecycleService implements NetworkUtils.OnNetworkStatusChangedListener {
|
||||
private static final String TAG = "SocketService";
|
||||
|
||||
private static final String SOCKET_URL = "wss://as.fuyingy.com/wss/device?sn=";
|
||||
/**
|
||||
* 恢复出厂与清除数据广播:Intent 没有公开常量,沿用固件约定的 action 字符串
|
||||
*/
|
||||
private static final String ACTION_FACTORY_RESET = "android.intent.action.FACTORY_RESET";
|
||||
private static final String ACTION_MASTER_CLEAR = "android.intent.action.MASTER_CLEAR";
|
||||
/**
|
||||
* 正常关闭码与关闭原因
|
||||
*/
|
||||
private static final int CLOSE_CODE_NORMAL = 1000;
|
||||
private static final String CLOSE_REASON = "客户端主动断开";
|
||||
/**
|
||||
* 心跳间隔,同时是断线重连的检查周期
|
||||
*/
|
||||
private static final long HEART_BEAT_RATE = 30 * 1000L;
|
||||
/**
|
||||
* 连接超时,WebSocket 是长连接,读超时必须为 0(不超时)
|
||||
*/
|
||||
private static final long CONNECT_TIMEOUT_SECONDS = 10L;
|
||||
/**
|
||||
* 网络恢复后的随机错峰区间,避免大批量设备在同一时刻连回服务端
|
||||
*/
|
||||
private static final long RECONNECT_JITTER_MIN = 0L;
|
||||
private static final long RECONNECT_JITTER_MAX = 30 * 1000L;
|
||||
|
||||
/**
|
||||
* 总容器:ON_DESTROY 一次 dispose,连带取消下面三个子容器里的所有订阅
|
||||
*/
|
||||
private final CompositeDisposable mDisposables = new CompositeDisposable();
|
||||
/**
|
||||
* 心跳流:stopHeartBeat 时 clear,亮屏后还能重新 add,不能用一次性 dispose
|
||||
*/
|
||||
private final CompositeDisposable mHeartBeatDisposables = new CompositeDisposable();
|
||||
/**
|
||||
* 建连任务:只保留最后一次,避免重复握手
|
||||
*/
|
||||
private final SerialDisposable mConnectDisposable = new SerialDisposable();
|
||||
/**
|
||||
* 错峰重连任务:后一次网络恢复覆盖前一次,天然去重
|
||||
*/
|
||||
private final SerialDisposable mReconnectDisposable = new SerialDisposable();
|
||||
|
||||
/**
|
||||
* WebSocket 专用客户端:不能复用 Retrofit 的 OkHttpManager(它带缓存和 30s 读超时)
|
||||
*/
|
||||
private final OkHttpClient mWebSocketClient = new OkHttpClient.Builder()
|
||||
.connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.writeTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.retryOnConnectionFailure(true)
|
||||
.build();
|
||||
|
||||
/**
|
||||
* 以下三个字段只在主线程读写,OkHttp 回调和网络回调都先 postToMain
|
||||
*/
|
||||
private boolean mConnecting;
|
||||
private boolean mOpened;
|
||||
private WebSocket mWebSocket;
|
||||
private ScreenLockReceiver mScreenLockReceiver;
|
||||
|
||||
private final LifecycleEventObserver mLifecycleObserver = new LifecycleEventObserver() {
|
||||
@Override
|
||||
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
|
||||
if (event == Lifecycle.Event.ON_CREATE) {
|
||||
onServiceCreated();
|
||||
} else if (event == Lifecycle.Event.ON_DESTROY) {
|
||||
onServiceDestroyed();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final WebSocketListener mWebSocketListener = new WebSocketListener() {
|
||||
@Override
|
||||
public void onOpen(WebSocket webSocket, Response response) {
|
||||
postToMain(() -> {
|
||||
// 不是当前连接说明建连期间已被主动断开(或已销毁),立刻取消掉,避免孤儿连接
|
||||
if (isDestroyed() || mWebSocket != webSocket) {
|
||||
webSocket.cancel();
|
||||
Log.e(TAG, "onOpen: 连接已失效,取消本次连接");
|
||||
return;
|
||||
}
|
||||
mOpened = true;
|
||||
Log.e(TAG, "onOpen: websocket连接成功");
|
||||
sendMsg(webSocket);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket webSocket, String text) {
|
||||
Log.e(TAG, "onMessage: " + text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosing(WebSocket webSocket, int code, String reason) {
|
||||
// OkHttp 要求收到服务端关闭帧后回一个 close,才能完成关闭握手
|
||||
webSocket.close(code, reason);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosed(WebSocket webSocket, int code, String reason) {
|
||||
Log.e(TAG, "onClosed: code = " + code + ", reason = " + reason);
|
||||
postToMain(() -> clearIfCurrent(webSocket));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
|
||||
Log.e(TAG, "onFailure: " + t);
|
||||
postToMain(() -> clearIfCurrent(webSocket));
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
// LifecycleService 在 onCreate 派发 ON_CREATE,这里注册观察者即可接管全部资源管理
|
||||
getLifecycle().addObserver(mLifecycleObserver);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
super.onStartCommand(intent, flags, startId);
|
||||
Log.e(TAG, "onStartCommand: startId = " + startId);
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
super.onBind(intent);
|
||||
// 双进程保活的 AIDL 绑定已移除,本服务不再提供绑定能力
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 OkHttp 回调和网络状态回调切回主线程,保证连接状态单点读写。
|
||||
*/
|
||||
private void postToMain(Runnable action) {
|
||||
AndroidSchedulers.mainThread().scheduleDirect(action);
|
||||
}
|
||||
|
||||
/**
|
||||
* ON_CREATE:注册监听、启动心跳流,连接由心跳流的首个 tick 触发。
|
||||
*/
|
||||
private void onServiceCreated() {
|
||||
mDisposables.add(mHeartBeatDisposables);
|
||||
mDisposables.add(mConnectDisposable);
|
||||
mDisposables.add(mReconnectDisposable);
|
||||
NetworkUtils.registerNetworkStatusChangedListener(this);
|
||||
registerScreenLockReceiver();
|
||||
startHeartBeat();
|
||||
Log.e(TAG, "onServiceCreated: 已启动websocket心跳流");
|
||||
}
|
||||
|
||||
/**
|
||||
* ON_DESTROY:取消所有 RxJava 订阅、注销监听与广播、关闭连接。
|
||||
*/
|
||||
private void onServiceDestroyed() {
|
||||
mDisposables.dispose();
|
||||
NetworkUtils.unregisterNetworkStatusChangedListener(this);
|
||||
ReceiverCompat.unregisterReceiver(this, mScreenLockReceiver);
|
||||
mScreenLockReceiver = null;
|
||||
closeConnect();
|
||||
Log.e(TAG, "onServiceDestroyed: 已释放websocket资源");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisconnected() {
|
||||
Log.e(TAG, "onDisconnected: 网络断开,连接状态交给心跳流检测");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnected(NetworkUtils.NetworkType networkType) {
|
||||
Log.e(TAG, "onConnected: " + networkType);
|
||||
// 网络回调可能在 binder 线程,连接状态只允许在主线程读写
|
||||
postToMain(() -> {
|
||||
if (isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
if (!SystemUtils.isScreenOn(this)) {
|
||||
Log.e(TAG, "onConnected: 息屏不重连");
|
||||
stopHeartBeat();
|
||||
return;
|
||||
}
|
||||
if (mWebSocket != null || mConnecting) {
|
||||
return;
|
||||
}
|
||||
scheduleNetworkReconnect();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 心跳流:RxJava 定时驱动连接检查。每次亮屏都重建心跳流,新流从 0 开始会立即
|
||||
* 检查一轮连接,同时保证始终只有一条流,不会叠加出多条心跳链。
|
||||
*/
|
||||
private void startHeartBeat() {
|
||||
if (isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
mHeartBeatDisposables.clear();
|
||||
mHeartBeatDisposables.add(Observable.interval(0, HEART_BEAT_RATE, TimeUnit.MILLISECONDS)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(tick -> checkConnection(),
|
||||
throwable -> Log.e(TAG, "startHeartBeat: " + throwable)));
|
||||
Log.e(TAG, "startHeartBeat: 已开启心跳检测");
|
||||
}
|
||||
|
||||
private void stopHeartBeat() {
|
||||
mHeartBeatDisposables.clear();
|
||||
Log.e(TAG, "stopHeartBeat: 已停止心跳检测");
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消排队中的建连任务与错峰重连 timer,避免息屏后仍有任务把连接建回来。
|
||||
*/
|
||||
private void cancelPendingConnect() {
|
||||
mConnectDisposable.set(null);
|
||||
mReconnectDisposable.set(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一轮连接检查:息屏直接停流,握手中跳过,已连接则发 ping,否则重建连接。
|
||||
*/
|
||||
private void checkConnection() {
|
||||
if (isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
// 息屏后不再重连,也不再等下一轮,等亮屏广播重新拉起心跳流
|
||||
if (!SystemUtils.isScreenOn(this)) {
|
||||
Log.e(TAG, "checkConnection: 息屏不重连");
|
||||
stopHeartBeat();
|
||||
return;
|
||||
}
|
||||
WebSocket current = mWebSocket;
|
||||
if (current != null) {
|
||||
if (!mOpened) {
|
||||
Log.e(TAG, "checkConnection: 握手中,跳过本轮");
|
||||
return;
|
||||
}
|
||||
if (sendMsg(current)) {
|
||||
return;
|
||||
}
|
||||
Log.e(TAG, "checkConnection: ping发送失败,重建连接");
|
||||
closeConnect();
|
||||
}
|
||||
connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 RxJava 在 IO 线程准备 Request,回到主线程后复查状态再发起 OkHttp 建连。
|
||||
* newWebSocket 本身是异步的,在主线程调用既不会阻塞,也能让状态变更串行化。
|
||||
*/
|
||||
private void connect() {
|
||||
if (isDestroyed() || !SystemUtils.isScreenOn(this) || mConnecting || mWebSocket != null) {
|
||||
return;
|
||||
}
|
||||
mConnecting = true;
|
||||
mConnectDisposable.set(Single.fromCallable(() -> new Request.Builder()
|
||||
.url(SOCKET_URL + Utils.getSerial())
|
||||
.build())
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(request -> {
|
||||
// 排队期间可能已经息屏、销毁或被主动断开,回主线程后必须再查一次
|
||||
if (!canConnect()) {
|
||||
mConnecting = false;
|
||||
Log.e(TAG, "connect: 状态已变化,放弃本次建连");
|
||||
return;
|
||||
}
|
||||
mConnecting = false;
|
||||
mWebSocket = mWebSocketClient.newWebSocket(request, mWebSocketListener);
|
||||
Log.e(TAG, "connect: 已发起websocket连接");
|
||||
}, throwable -> {
|
||||
mConnecting = false;
|
||||
Log.e(TAG, "connect: 建连失败 " + throwable);
|
||||
}));
|
||||
}
|
||||
|
||||
private boolean canConnect() {
|
||||
return !isDestroyed() && SystemUtils.isScreenOn(this) && mWebSocket == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络恢复是全量设备同时触发的事件,用带抖动的单次任务错峰后再检查连接。
|
||||
*/
|
||||
private void scheduleNetworkReconnect() {
|
||||
if (isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
long delay = TimeUtils.randomDelay(RECONNECT_JITTER_MIN, RECONNECT_JITTER_MAX);
|
||||
Log.e(TAG, "scheduleNetworkReconnect: 网络恢复, 错峰延时 = " + delay);
|
||||
mReconnectDisposable.set(Observable.timer(delay, TimeUnit.MILLISECONDS)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(tick -> checkConnection(),
|
||||
throwable -> Log.e(TAG, "scheduleNetworkReconnect: " + throwable)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接关闭或失败:只清理属于当前连接的回调,旧连接迟到的回调不能影响新连接;
|
||||
* 不在这里直接重连,统一由心跳流按屏幕状态决定。
|
||||
*/
|
||||
private void clearIfCurrent(WebSocket webSocket) {
|
||||
if (mWebSocket != webSocket) {
|
||||
return;
|
||||
}
|
||||
mWebSocket = null;
|
||||
mOpened = false;
|
||||
mConnecting = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报设备在线心跳,send 返回 false 表示连接已不可用。
|
||||
*/
|
||||
private boolean sendMsg(WebSocket webSocket) {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("sn", Utils.getSerial());
|
||||
jsonObject.addProperty("type", "ping");
|
||||
try {
|
||||
boolean sent = webSocket.send(jsonObject.toString());
|
||||
Log.e(TAG, "sendMsg: " + jsonObject + ", sent = " + sent);
|
||||
return sent;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "sendMsg: 发送失败 " + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void closeConnect() {
|
||||
WebSocket current = mWebSocket;
|
||||
mWebSocket = null;
|
||||
mOpened = false;
|
||||
mConnecting = false;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
current.close(CLOSE_CODE_NORMAL, CLOSE_REASON);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "closeConnect: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册屏幕状态广播,只用于管理连接时机(亮屏重连、息屏断开),不用于把服务拉起来。
|
||||
*/
|
||||
private void registerScreenLockReceiver() {
|
||||
if (mScreenLockReceiver != null) {
|
||||
return;
|
||||
}
|
||||
mScreenLockReceiver = new ScreenLockReceiver();
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
|
||||
filter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
filter.addAction(Intent.ACTION_SCREEN_ON);
|
||||
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
|
||||
filter.addAction(Intent.ACTION_USER_PRESENT);
|
||||
filter.addAction(Intent.ACTION_SHUTDOWN);
|
||||
filter.addAction(ACTION_FACTORY_RESET);
|
||||
filter.addAction(ACTION_MASTER_CLEAR);
|
||||
// 只接收系统广播,API 33+ 必须显式声明导出标志,否则注册会抛异常导致服务创建失败
|
||||
ReceiverCompat.registerReceiver(this, mScreenLockReceiver, filter,
|
||||
ReceiverCompat.RECEIVER_NOT_EXPORTED);
|
||||
}
|
||||
|
||||
private class ScreenLockReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
Log.e(TAG, "onReceive: action = " + action);
|
||||
if (TextUtils.isEmpty(action)) {
|
||||
Log.e(TAG, "onReceive: action 为空");
|
||||
return;
|
||||
}
|
||||
// 广播回调里只提交 RxJava 订阅,连接动作由订阅切到 IO/主线程执行,不在 onReceive 里做
|
||||
if (Intent.ACTION_BOOT_COMPLETED.equals(action)
|
||||
|| Intent.ACTION_USER_PRESENT.equals(action)
|
||||
|| Intent.ACTION_SCREEN_ON.equals(action)) {
|
||||
Log.e(TAG, "onReceive: 亮屏,重新开启心跳检测");
|
||||
startHeartBeat();
|
||||
} else if (Intent.ACTION_SCREEN_OFF.equals(action)
|
||||
|| Intent.ACTION_SHUTDOWN.equals(action)
|
||||
|| ACTION_FACTORY_RESET.equals(action)
|
||||
|| ACTION_MASTER_CLEAR.equals(action)) {
|
||||
Log.e(TAG, "onReceive: 息屏,主动断开websocket");
|
||||
stopHeartBeat();
|
||||
cancelPendingConnect();
|
||||
closeConnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDestroyed() {
|
||||
return getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED;
|
||||
}
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
package com.fuying.sn.service;
|
||||
|
||||
/**
|
||||
* 作者 mjsheng
|
||||
* 日期 2019/4/1 10:57
|
||||
* 邮箱 501802639@qq.com
|
||||
* 来自:
|
||||
*/
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.Binder;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.blankj.utilcode.util.NetworkUtils;
|
||||
import com.fuying.sn.KeepAliveConnection;
|
||||
import com.fuying.sn.utils.JgyUtils;
|
||||
import com.fuying.sn.utils.ServiceAliveUtils;
|
||||
import com.fuying.sn.utils.Utils;
|
||||
import com.fuying.sn.websocket.JWebSocketClient;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* 主进程 双进程通讯
|
||||
*
|
||||
* @author LiGuangMin
|
||||
* @time Created by 2018/8/17 11:26
|
||||
*/
|
||||
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
|
||||
private static final String TAG = "StepService";
|
||||
|
||||
public JWebSocketClient client;
|
||||
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
|
||||
|
||||
@Override
|
||||
public void onDisconnected() {
|
||||
Log.i("JWebSocketClientService", "网络断开连接");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnected(NetworkUtils.NetworkType networkType) {
|
||||
Log.i("JWebSocketClientService", "网络已连接");
|
||||
// connect();
|
||||
}
|
||||
|
||||
//用于Activity和service通讯
|
||||
public class JWebSocketClientBinder extends Binder {
|
||||
public StepService getService() {
|
||||
return StepService.this;
|
||||
}
|
||||
}
|
||||
|
||||
private ServiceConnection mServiceConnection = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
|
||||
Log.w(TAG, "StepService:建立链接");
|
||||
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(StepService.this, GuardService.class.getName());
|
||||
if (!isServiceRunning) {
|
||||
Intent i = new Intent(StepService.this, GuardService.class);
|
||||
startService(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName componentName) {
|
||||
// 断开链接
|
||||
startService(new Intent(StepService.this, GuardService.class));
|
||||
// 重新绑定
|
||||
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return new KeepAliveConnection.Stub() {
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
NetworkUtils.registerNetworkStatusChangedListener(this);
|
||||
registerScreenLockReceiver();
|
||||
//初始化websocket
|
||||
initSocketClient();
|
||||
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
// 绑定建立链接
|
||||
Log.e("JWebSocketClientService", "onStartCommand: ");
|
||||
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
private ScreenLockReceiver screenLockReceiver;
|
||||
|
||||
private void registerScreenLockReceiver() {
|
||||
if (null == screenLockReceiver) {
|
||||
screenLockReceiver = new ScreenLockReceiver();
|
||||
}
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
|
||||
filter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
filter.addAction(Intent.ACTION_SCREEN_ON);
|
||||
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
|
||||
filter.addAction(Intent.ACTION_USER_PRESENT);
|
||||
filter.addAction(Intent.ACTION_SHUTDOWN);
|
||||
filter.addAction(Intent.ACTION_FACTORY_RESET);
|
||||
filter.addAction(Intent.ACTION_MASTER_CLEAR);
|
||||
registerReceiver(screenLockReceiver, filter);
|
||||
}
|
||||
|
||||
private class ScreenLockReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
Log.e(TAG, "onReceive:" + action);
|
||||
if (TextUtils.isEmpty(action)) {
|
||||
Log.e(TAG, "onReceive: is NULL");
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
case Intent.ACTION_BOOT_COMPLETED:
|
||||
case Intent.ACTION_USER_PRESENT:
|
||||
case Intent.ACTION_SCREEN_ON:
|
||||
mHandler.post(heartBeatRunnable);//开启心跳检测
|
||||
// sendMsg(1);
|
||||
break;
|
||||
case Intent.ACTION_SCREEN_OFF:
|
||||
case Intent.ACTION_SHUTDOWN:
|
||||
case Intent.ACTION_FACTORY_RESET:
|
||||
case Intent.ACTION_MASTER_CLEAR:
|
||||
closeConnect();
|
||||
// sendMsg(0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
NetworkUtils.unregisterNetworkStatusChangedListener(this);
|
||||
closeConnect();
|
||||
if (screenLockReceiver != null) {
|
||||
unregisterReceiver(screenLockReceiver);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化websocket连接
|
||||
*/
|
||||
private void initSocketClient() {
|
||||
URI uri = URI.create("wss://as.fuyingy.com/wss/device?sn=" + Utils.getSerial());
|
||||
// URI uri = URI.create(BuildConfig.WEBSOCKET_URL);
|
||||
// URI uri = URI.create("ws://echo.websocket.org");
|
||||
// URI uri = URI.create("ws://123.207.136.134:9010/ajaxchattest");
|
||||
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连接成功");
|
||||
// sendMsg(1);
|
||||
sendMsg();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
super.onClose(code, reason, remote);
|
||||
Log.i("JWebSocketClientService", "websocket连接关闭:" + reason);
|
||||
// client.close();
|
||||
// initSocketClient();
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
mHandler.postDelayed(heartBeatRunnable, 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()) {
|
||||
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "postDelayed off");
|
||||
}
|
||||
}
|
||||
};
|
||||
connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接websocket
|
||||
*/
|
||||
private void connect() {
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
|
||||
Log.i("JWebSocketClientService", "websocket链接中");
|
||||
client.connectBlocking();
|
||||
} catch (Exception e) {
|
||||
Log.i("JWebSocketClientService", e.getMessage());
|
||||
// e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*/
|
||||
public void sendMsg() {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("sn", Utils.getSerial());
|
||||
// PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
|
||||
// if (!pm.isScreenOn()) {
|
||||
// jsonObject.addProperty("online", 0);
|
||||
// //熄屏状态
|
||||
// } else {
|
||||
// jsonObject.addProperty("online", 1);
|
||||
// }
|
||||
jsonObject.addProperty("type", "ping");
|
||||
if (null != client) {
|
||||
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
|
||||
client.send(jsonObject.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void sendMsg(int state) {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("sn", Utils.getSerial());
|
||||
jsonObject.addProperty("online", state);
|
||||
if (null != client) {
|
||||
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
|
||||
try {
|
||||
client.send(jsonObject.toString());
|
||||
} catch (Exception e) {
|
||||
Log.i(TAG, "sendMsg :" + e.getLocalizedMessage());
|
||||
}
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "未连接");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接
|
||||
*/
|
||||
private void closeConnect() {
|
||||
try {
|
||||
if (null != client) {
|
||||
client.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
client = null;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------websocket心跳检测------------------------------------------------
|
||||
private static final long HEART_BEAT_RATE = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
|
||||
private Handler mHandler = new Handler();
|
||||
private Runnable heartBeatRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态");
|
||||
if (client != null) {
|
||||
if (client.isOpen()) {
|
||||
Log.i("JWebSocketClientService", "websocket已连接");
|
||||
sendMsg();
|
||||
} else if (client.isClosed()) {
|
||||
Log.i("JWebSocketClientService", "websocket重连中");
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
reconnectWs();
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "reconnectWs off");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//如果client已为空,重新初始化连接
|
||||
client = null;
|
||||
initSocketClient();
|
||||
}
|
||||
//每隔一定的时间,对长连接进行一次心跳检测
|
||||
if (JgyUtils.getInstance().isScreenOn()) {
|
||||
mHandler.postDelayed(this, HEART_BEAT_RATE);
|
||||
} else {
|
||||
Log.i("JWebSocketClientService", "websocket息屏不重连");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 开启重连
|
||||
*/
|
||||
private void reconnectWs() {
|
||||
mHandler.removeCallbacks(heartBeatRunnable);
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Log.i("JWebSocketClientService", "开启重连");
|
||||
client.reconnectBlocking();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
}
|
||||
@@ -39,16 +39,14 @@ import com.fuying.sn.network.RequestCompletion;
|
||||
import com.fuying.sn.network.UrlAddress;
|
||||
import com.fuying.sn.rlog.LogDBManager;
|
||||
import com.fuying.sn.service.DownloadService;
|
||||
import com.fuying.sn.service.GuardService;
|
||||
import com.fuying.sn.service.StepService;
|
||||
import com.fuying.sn.service.SocketService;
|
||||
import com.fuying.sn.sync.AppInventorySync;
|
||||
import com.fuying.sn.sync.AppUsageReporter;
|
||||
import com.fuying.sn.sync.DeviceProfileSync;
|
||||
import com.fuying.sn.utils.ApkUtils;
|
||||
import com.fuying.sn.utils.CacheUtils;
|
||||
import com.fuying.sn.utils.JgyUtils;
|
||||
import com.fuying.sn.utils.NetStateUtils;
|
||||
import com.fuying.sn.utils.SPUtils;
|
||||
import com.fuying.sn.utils.SystemUtils;
|
||||
import com.fuying.sn.utils.TimeUtils;
|
||||
import com.fuying.sn.utils.ToastUtil;
|
||||
import com.fuying.sn.utils.Utils;
|
||||
@@ -138,13 +136,13 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
|
||||
boolean reconnect = mReconnectSyncPending;
|
||||
mStartupSyncPending = false;
|
||||
mReconnectSyncPending = false;
|
||||
if ((!startup && !reconnect) || !NetStateUtils.isNetworkConnected(this)) {
|
||||
if ((!startup && !reconnect) || !SystemUtils.isNetworkConnected(this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 安装清单同步只依赖后台服务和网络,息屏时也能补报。
|
||||
TimeManager.getInstance().syncInstalledApps();
|
||||
boolean screenOnReconnect = reconnect && JgyUtils.getInstance().isScreenOn();
|
||||
boolean screenOnReconnect = reconnect && SystemUtils.isScreenOn(this);
|
||||
if (!startup && !screenOnReconnect) {
|
||||
return;
|
||||
}
|
||||
@@ -260,7 +258,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
|
||||
String aole_app_forbid = Settings.System.getString(getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID);
|
||||
ApkUtils.writeAppPackageList(MainService.this, aole_app_forbid);
|
||||
|
||||
new CacheUtils().cleanApplicationUserData(this, "com.aoleyun.os");
|
||||
ApkUtils.cleanApplicationUserDataAsync(this, "com.aoleyun.os", null);
|
||||
File file = new File(JgyUtils.getInstance().getDownLoadPath());
|
||||
Log.e(TAG, "versionIsUpdate: " + file.getAbsolutePath());
|
||||
String[] fileList = file.list();
|
||||
@@ -289,8 +287,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
|
||||
}
|
||||
|
||||
private void startService() {
|
||||
startService(new Intent(this, GuardService.class));
|
||||
startService(new Intent(this, StepService.class));
|
||||
startService(new Intent(this, SocketService.class));
|
||||
startService(new Intent(this, DownloadService.class));
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ import com.fuying.sn.sync.DeviceSettingsSync;
|
||||
import com.fuying.sn.sync.RequestCallbacks;
|
||||
import com.fuying.sn.sync.TimePolicySync;
|
||||
import com.fuying.sn.utils.SPUtils;
|
||||
import com.fuying.sn.utils.ServiceAliveUtils;
|
||||
import com.fuying.sn.utils.SystemUtils;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.tencent.mmkv.MMKV;
|
||||
|
||||
@@ -279,7 +279,7 @@ public class MainServiceModel extends BaseAndroidViewModel {
|
||||
if (code == 200) {
|
||||
JsonObject jsonObject = GsonUtils.getJsonObject(GsonUtils.toJSONString(baseResponse.data));
|
||||
int is_screen_lock = jsonObject.get("is_screen_lock").getAsInt();
|
||||
if (!ServiceAliveUtils.isServiceAlive(getApplication(), ManagerService.class.getName())) {
|
||||
if (!SystemUtils.isServiceAlive(getApplication(), ManagerService.class.getName())) {
|
||||
getApplication().startService(new Intent(getApplication(), ManagerService.class));
|
||||
}
|
||||
SPUtils.put(getApplication(), ManagerService.LOCK_STATE, is_screen_lock);
|
||||
|
||||
Reference in new issue
Block a user