refactor(network): 重构 WebSocket 重连与重试机制并简化定位回调

- RetryCallback 使用 canceled/finished 状态与守护线程定时器,修复并发取消与响应处理
- StepService 增加连接生命周期控制、原子化连接与统一心跳调度,销毁时正确解绑
- PushManager 定位流程改由 MapManager 内部处理回调
This commit is contained in:
tongtong committed 2026-11-02 10:34:22 +08:00
1 parent 497af25e2e
commit 17837a1ad3
3 files changed
+96 -140

No files matched your search

@@ -19,41 +19,54 @@ public abstract class RetryCallback<T> implements Callback<T> {
private int mCurrentRetryCount;
private boolean isExecuting;
private boolean canceled;
private boolean finished;
private Call<T> mCall;
private Timer timer = new Timer();
private Timer timer = new Timer("network-retry", true);
public RetryCallback(Call<T> call, int retryCount, long retryInterval) {
isExecuting = true;
mCall = call;
mRetryCount = retryCount;
mRetryInterval = retryInterval;
}
@Override
public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
public final synchronized void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
Log.e(TAG, "onResponse");
isExecuting = false;
if (canceled || finished) {
if (response.errorBody() != null) response.errorBody().close();
return;
}
if (!response.isSuccessful() && mCurrentRetryCount < mRetryCount) {
if (response.errorBody() != null) response.errorBody().close();
mCurrentRetryCount++;
retryRequest(call);
} else {
finished = true;
timer.cancel();
onRequestResponse(call, response);
}
}
@Override
public final void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
public final synchronized void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
Log.e(TAG, "onFailure");
isExecuting = false;
if (canceled || finished) return;
if (call.isCanceled()) {
canceled = true;
timer.cancel();
return;
}
if (mCurrentRetryCount < mRetryCount) {
mCurrentRetryCount++;
Log.e(TAG, "onFailure: " + "RetryCount: " + mCurrentRetryCount);
Log.e(TAG, "onFailure: " + "RetryResponse: " + call.request());
retryRequest(call);
} else {
finished = true;
timer.cancel();
onRequestFail(call, t);
}
}
@@ -61,27 +74,24 @@ public abstract class RetryCallback<T> implements Callback<T> {
private void retryRequest(final Call<T> call) {
Log.e(TAG, "retryRequest");
onStartRetry();
if (canceled || finished) return;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
synchronized (RetryCallback.this) {
if (canceled || finished) return;
mCall = call.clone();
mCall.enqueue(RetryCallback.this);
isExecuting = true;
}
}
};
timer.schedule(timerTask, mRetryInterval);
}
public void cancelCall() {
synchronized (this) {
if (!isExecuting) {
timer.cancel();
} else {
mCall.cancel();
}
}
public synchronized void cancelCall() {
canceled = true;
timer.cancel();
mCall.cancel();
}
public abstract void onRequestResponse(Call call, Response response);
@@ -58,8 +58,6 @@ import com.aoleyun.sn.utils.SysSettingUtils;
import com.aoleyun.sn.utils.TimeUtils;
import com.aoleyun.sn.utils.Utils;
import com.arialyy.aria.core.Aria;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
@@ -445,88 +443,7 @@ public class PushManager {
getBatteryInfo(mContext);
sendRefreshBroadcast(mContext);
//定位前记录并临时开启系统定位设置,定位结束自动还原
MapManager.getInstance().startLocation(new BDAbstractLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
if (null != location) {
switch (location.getLocType()) {
case BDLocation.TypeGpsLocation:// GPS定位结果
case BDLocation.TypeNetWorkLocation:// 网络定位结果
case BDLocation.TypeOffLineLocation:// 离线定位结果
Log.e(TAG, "onLocationChanged: " + "定位成功");
Log.e(TAG, "onLocationChanged: " + location.getAddrStr() + location.getLocationDescribe());
mMMKV.encode("MapAddress", location.getAddrStr() + location.getLocationDescribe());
mMMKV.encode("longitude", String.valueOf(location.getLongitude()));
mMMKV.encode("latitude", String.valueOf(location.getLatitude()));
mMMKV.encode("MapError", "-");
break;
case BDLocation.TypeServerError:
Log.e(TAG, "onReceiveLocation: " + "服务端网络定位失败");
mMMKV.encode("MapError", "服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
break;
case BDLocation.TypeNetWorkException:
Log.e(TAG, "onReceiveLocation: " + "网络不同导致定位失败,请检查网络是否通畅");
mMMKV.encode("MapError", "网络不同导致定位失败,请检查网络是否通畅");
break;
case BDLocation.TypeCriteriaException:
Log.e(TAG, "onReceiveLocation: " + "无法获取有效定位依据导致定位失败");
mMMKV.encode("MapError", "无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
break;
default:
}
}
Log.e(TAG, "MapAddress: " + mMMKV.decodeString("MapAddress", "-"));
Log.e(TAG, "MapError: " + mMMKV.decodeString("MapError", "-"));
//定位结束(成功或失败),停止定位并还原定位前的系统设置
MapManager.getInstance().stopLocation();
}
@Override
public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
StringBuffer sb = new StringBuffer(256);
sb.append("诊断结果: ");
if (locType == BDLocation.TypeNetWorkLocation) {
if (diagnosticType == 1) {
sb.append("网络定位成功,没有开启GPS,建议打开GPS会更好");
sb.append("\n" + diagnosticMessage);
} else if (diagnosticType == 2) {
sb.append("网络定位成功,没有开启Wi-Fi,建议打开Wi-Fi会更好");
sb.append("\n" + diagnosticMessage);
}
} else if (locType == BDLocation.TypeOffLineLocationFail) {
if (diagnosticType == 3) {
sb.append("定位失败,请您检查您的网络状态");
sb.append("\n" + diagnosticMessage);
}
} else if (locType == BDLocation.TypeCriteriaException) {
if (diagnosticType == 4) {
sb.append("定位失败,无法获取任何有效定位依据");
sb.append("\n" + diagnosticMessage);
} else if (diagnosticType == 5) {
sb.append("定位失败,无法获取有效定位依据,请检查运营商网络或者Wi-Fi网络是否正常开启,尝试重新请求定位");
sb.append(diagnosticMessage);
} else if (diagnosticType == 6) {
sb.append("定位失败,无法获取有效定位依据,请尝试插入一张sim卡或打开Wi-Fi重试");
sb.append("\n" + diagnosticMessage);
} else if (diagnosticType == 7) {
sb.append("定位失败,飞行模式下无法获取有效定位依据,请关闭飞行模式重试");
sb.append("\n" + diagnosticMessage);
} else if (diagnosticType == 9) {
sb.append("定位失败,无法获取任何有效定位依据");
sb.append("\n" + diagnosticMessage);
}
} else if (locType == BDLocation.TypeServerError) {
if (diagnosticType == 8) {
sb.append("定位失败,请确认您定位的开关打开状态,是否赋予APP定位权限");
sb.append("\n" + diagnosticMessage);
}
}
Log.e(TAG, "onLocationChanged: " + "定位失败");
mMMKV.encode("MapError", sb.toString());
Log.e(TAG, "onLocDiagnosticMessage: " + sb);
}
});
MapManager.getInstance().startLocation();
break;
case LOCK_SCREEN:
Toaster.debugShow("收到管控:屏幕锁定");
@@ -10,6 +10,8 @@ import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
@@ -27,6 +29,7 @@ import com.google.gson.JsonObject;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 主进程 双进程通讯
@@ -37,7 +40,11 @@ import java.net.URI;
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
private final static String TAG = "StepService";
public JWebSocketClient client;
public volatile JWebSocketClient client;
private volatile boolean destroyed;
private volatile boolean connectionEnabled = true;
private boolean guardBound;
private final AtomicBoolean connecting = new AtomicBoolean();
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
// 新增防抖控制变量
@@ -76,9 +83,9 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
if (destroyed) return;
startService(new Intent(StepService.this, GuardService.class));
// 重新绑定
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
// 已有绑定会在目标服务恢复后自动重连。
}
};
@@ -96,7 +103,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
registerScreenLockReceiver();
//初始化websocket
initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
}
@Override
@@ -104,7 +111,9 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
// startForeground(1, new Notification());
// 绑定建立链接
Log.e("JWebSocketClientService", "onStartCommand: ");
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
if (!guardBound) {
guardBound = bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
return START_STICKY;
}
@@ -141,6 +150,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
case Intent.ACTION_BOOT_COMPLETED:
case Intent.ACTION_USER_PRESENT:
case Intent.ACTION_SCREEN_ON:
connectionEnabled = true;
mHandler.removeCallbacks(heartBeatRunnable);
mHandler.post(heartBeatRunnable);//开启心跳检测
sendMsg();
@@ -150,7 +160,8 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
case Intent.ACTION_REBOOT:
case Intent.ACTION_FACTORY_RESET:
case Intent.ACTION_MASTER_CLEAR:
mHandler.removeCallbacks(heartBeatRunnable);
connectionEnabled = false;
mHandler.removeCallbacksAndMessages(null);
closeConnect();
break;
default:
@@ -162,6 +173,13 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
@Override
public void onDestroy() {
super.onDestroy();
destroyed = true;
connectionEnabled = false;
mHandler.removeCallbacksAndMessages(null);
if (guardBound) {
unbindService(mServiceConnection);
guardBound = false;
}
NetworkUtils.unregisterNetworkStatusChangedListener(this);
closeConnect();
if (screenLockReceiver != null) {
@@ -173,6 +191,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
* 初始化websocket连接
*/
private void initSocketClient() {
if (destroyed || !connectionEnabled || connecting.get()) return;
URI uri = URI.create(BuildConfig.WEBSOCKET_URL + "device?sn=" + Utils.getSerial(StepService.this));
client = new JWebSocketClient(uri) {
@Override
@@ -184,9 +203,13 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.i("JWebSocketClientService", "websocket连接成功");
mHandler.postDelayed(() -> {
if (isOpen()) sendMsg();
}, 1000);
mHandler.post(() -> {
if (!destroyed && connectionEnabled && client == this) {
lastMessageTime = 0;
sendMsg();
scheduleHeartbeat(HEART_BEAT_RATE);
}
});
}
@Override
@@ -196,7 +219,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
// client.close();
// initSocketClient();
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
}
}
@@ -207,7 +230,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
// client.close();
// initSocketClient();
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
scheduleHeartbeat(HEART_BEAT_RATE);//开启心跳检测
} else {
Log.i("JWebSocketClientService", "postDelayed off");
}
@@ -220,19 +243,26 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
* 连接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();
}
connectSocket(false);
}
private void connectSocket(boolean reconnect) {
final JWebSocketClient socket = client;
if (destroyed || !connectionEnabled || socket == null || !connecting.compareAndSet(false, true))
return;
new Thread(() -> {
try {
if (destroyed || !connectionEnabled || socket != client) return;
if (reconnect) socket.reconnectBlocking();
else socket.connectBlocking();
} catch (Exception e) {
Log.e(TAG, "WebSocket connection failed", e);
} finally {
connecting.set(false);
if (destroyed || !connectionEnabled || socket != client) socket.close();
scheduleHeartbeat(HEART_BEAT_RATE);
}
}.start();
}, "device-websocket-connect").start();
}
/**
@@ -240,9 +270,9 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
*/
public void sendMsg() {
synchronized (sendLock) {
long currentTime = System.currentTimeMillis();
long currentTime = SystemClock.elapsedRealtime();
// 检查时间间隔和连接状态
if (currentTime - lastMessageTime < MIN_MESSAGE_INTERVAL) {
if (lastMessageTime != 0 && currentTime - lastMessageTime < MIN_MESSAGE_INTERVAL) {
Log.w("JWebSocketClientService", "消息发送过于频繁,已忽略");
return;
}
@@ -283,13 +313,23 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
// -------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
private Handler mHandler = new Handler();
private final Handler mHandler = new Handler(Looper.getMainLooper());
private void scheduleHeartbeat(long delay) {
if (destroyed || !connectionEnabled) return;
mHandler.post(() -> {
mHandler.removeCallbacks(heartBeatRunnable);
if (!destroyed && connectionEnabled) mHandler.postDelayed(heartBeatRunnable, delay);
});
}
private Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
if (destroyed || !connectionEnabled) return;
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client == null) {
initSocketClient();
scheduleHeartbeat(HEART_BEAT_RATE);
return;
}
@@ -307,7 +347,7 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
//每隔一定的时间,对长连接进行一次心跳检测
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(this, HEART_BEAT_RATE);
scheduleHeartbeat(HEART_BEAT_RATE);
} else {
Log.i("JWebSocketClientService", "websocket息屏不重连");
}
@@ -318,17 +358,6 @@ public class StepService extends Service implements NetworkUtils.OnNetworkStatus
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(heartBeatRunnable);
new Thread() {
@Override
public void run() {
try {
Log.i("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
connectSocket(true);
}
}
}