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(); } } }