makcar/app/src/main/java/com/aros/apron/callback/MqttActionCallBack.java

84 lines
3.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.aros.apron.callback;
import android.os.Handler;
import android.os.Looper;
import com.aros.apron.constant.AMSConfig;
import com.aros.apron.tools.LogUtil;
import com.aros.apron.tools.ToastUtil;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
public class MqttActionCallBack implements IMqttActionListener {
private final String TAG = "MqttActionCallBack";
private MqttAndroidClient mqttAndroidClient;
private MqttConnectOptions options;
private int reconnectAttempt = 0;
private static final int INITIAL_RETRY_INTERVAL = 3000; // 初始重试间隔 3 秒
private static final int MAX_RETRY_INTERVAL = 30000; // 最大重试间隔 30 秒
private static final Handler retryHandler = new Handler(Looper.getMainLooper());
private Runnable retryRunnable;
public MqttActionCallBack(MqttAndroidClient mqttAndroidClient, MqttConnectOptions options) {
this.mqttAndroidClient = mqttAndroidClient;
this.options = options;
}
@Override
public void onSuccess(IMqttToken asyncActionToken) {
LogUtil.log(TAG, "MQtt连接成功-------");
reconnectAttempt = 0;
if (retryRunnable != null) {
retryHandler.removeCallbacks(retryRunnable);
retryRunnable = null;
}
new Handler(Looper.getMainLooper()).post(() -> ToastUtil.showToast("MQtt连接成功"));
try {
mqttAndroidClient.subscribe(AMSConfig.DOWN_UAV_SERVICES, 1);
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LogUtil.log(TAG, "MQtt连接失败:" + exception.toString());
try {
if (!mqttAndroidClient.isConnected()) {
reconnectAttempt++;
// 指数退避3s → 6s → 12s → 24s → 30s(封顶)
long retryDelay = Math.min(INITIAL_RETRY_INTERVAL * (1L << Math.min(reconnectAttempt, 4)), MAX_RETRY_INTERVAL);
if (reconnectAttempt % 10 == 0 || reconnectAttempt <= 3) {
LogUtil.log(TAG, "" + reconnectAttempt + " 次重连,间隔 " + retryDelay + "ms");
}
if (retryRunnable != null) {
retryHandler.removeCallbacks(retryRunnable);
}
final long finalDelay = retryDelay;
retryRunnable = new Runnable() {
@Override
public void run() {
try {
mqttAndroidClient.connect(options, null, MqttActionCallBack.this);
} catch (MqttException e) {
LogUtil.log(TAG, "mqtt重连异常:" + e.toString());
}
}
};
retryHandler.postDelayed(retryRunnable, finalDelay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}