android MQTT封装

单纯的记录一下代码

  1. build.gradle

    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

  2. activity_mian.xml

    <?xml version="1.0" encoding="utf-8"?>

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" tools:context=".MainActivity">

    复制代码
     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:padding="16dp">
    
         <!-- 标题 -->
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_marginBottom="24dp"
             android:gravity="center"
             android:text="MQTT客户端演示"
             android:textColor="@color/colorPrimary"
             android:textSize="24sp"
             android:textStyle="bold" />
    
         <!-- 连接控制区 -->
         <androidx.cardview.widget.CardView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_marginBottom="16dp"
             app:cardCornerRadius="8dp"
             app:cardElevation="4dp">
    
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
                 android:padding="16dp">
    
                 <TextView
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp"
                     android:text="连接控制"
                     android:textSize="18sp"
                     android:textStyle="bold" />
    
                 <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:orientation="horizontal">
    
                     <Button
                         android:id="@+id/btn_connect"
                         style="@style/Widget.AppCompat.Button.Colored"
                         android:layout_width="0dp"
                         android:layout_height="wrap_content"
                         android:layout_marginEnd="8dp"
                         android:layout_weight="1"
                         android:text="连接" />
    
                     <Button
                         android:id="@+id/btn_disconnect"
                         style="@style/Widget.AppCompat.Button.Colored"
                         android:layout_width="0dp"
                         android:layout_height="wrap_content"
                         android:layout_marginStart="8dp"
                         android:layout_weight="1"
                         android:text="断开" />
    
                 </LinearLayout>
             </LinearLayout>
         </androidx.cardview.widget.CardView>
    
         <!-- 订阅区 -->
         <androidx.cardview.widget.CardView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_marginBottom="16dp"
             app:cardCornerRadius="8dp"
             app:cardElevation="4dp">
    
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
                 android:padding="16dp">
    
                 <TextView
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp"
                     android:text="主题订阅"
                     android:textSize="18sp"
                     android:textStyle="bold" />
    
                 <com.google.android.material.textfield.TextInputLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp">
    
                     <EditText
                         android:id="@+id/et_subscribe_topic"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:hint="输入订阅主题"
                         android:textSize="16sp" />
                 </com.google.android.material.textfield.TextInputLayout>
    
                 <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:orientation="horizontal">
    
                     <Button
                         android:id="@+id/btn_subscribe"
                         style="@style/Widget.AppCompat.Button.Colored"
                         android:layout_width="0dp"
                         android:layout_height="wrap_content"
                         android:layout_marginEnd="8dp"
                         android:layout_weight="1"
                         android:text="订阅" />
    
                     <Button
                         android:id="@+id/btn_unsubscribe"
                         style="@style/Widget.AppCompat.Button.Colored"
                         android:layout_width="0dp"
                         android:layout_height="wrap_content"
                         android:layout_marginStart="8dp"
                         android:layout_weight="1"
                         android:text="取消订阅" />
    
                 </LinearLayout>
             </LinearLayout>
         </androidx.cardview.widget.CardView>
    
         <!-- 消息发送区 -->
         <androidx.cardview.widget.CardView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_marginBottom="16dp"
             app:cardCornerRadius="8dp"
             app:cardElevation="4dp">
    
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
                 android:padding="16dp">
    
                 <TextView
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp"
                     android:text="消息发送"
                     android:textSize="18sp"
                     android:textStyle="bold" />
    
                 <com.google.android.material.textfield.TextInputLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp">
    
                     <EditText
                         android:id="@+id/et_topic"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:hint="目标主题"
                         android:textSize="16sp" />
                 </com.google.android.material.textfield.TextInputLayout>
    
                 <com.google.android.material.textfield.TextInputLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="16dp">
    
                     <EditText
                         android:id="@+id/et_message"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:gravity="top"
                         android:hint="消息内容"
                         android:minLines="3"
                         android:textSize="16sp" />
                 </com.google.android.material.textfield.TextInputLayout>
    
                 <Button
                     android:id="@+id/btn_send"
                     style="@style/Widget.AppCompat.Button.Colored"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:text="发送消息" />
    
             </LinearLayout>
         </androidx.cardview.widget.CardView>
    
         <!-- 日志显示区 -->
         <androidx.cardview.widget.CardView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             app:cardCornerRadius="8dp"
             app:cardElevation="4dp">
    
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
                 android:padding="16dp">
    
                 <TextView
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_marginBottom="12dp"
                     android:text="日志信息"
                     android:textSize="18sp"
                     android:textStyle="bold" />
    
                 <ScrollView
                     android:id="@+id/scroll_view"
                     android:layout_width="match_parent"
                     android:layout_height="200dp"
                     android:background="#f5f5f5"
                     android:padding="8dp">
    
                     <TextView
                         android:id="@+id/tv_log"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:fontFamily="monospace"
                         android:text="等待操作...\n"
                         android:textSize="14sp" />
                 </ScrollView>
             </LinearLayout>
         </androidx.cardview.widget.CardView>
     </LinearLayout>
    </ScrollView>
  3. MainActivity.java

    package cn.wx.mqtt;

    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.IBinder;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ScrollView;
    import android.widget.TextView;
    import android.widget.Toast;

    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity implements MQTTManager.MQTTCallback {
    private static final String TAG = "MQTTDemoActivity";

    复制代码
     private MQTTService mqttService;
     private boolean isBound = false;
     private Handler mainHandler;
    
     // UI组件
     private Button connectButton;
     private Button disconnectButton;
     private Button subscribeButton;
     private Button unsubscribeButton;
     private Button sendButton;
     private EditText topicEditText;
     private EditText messageEditText;
     private EditText subscribeTopicEditText;
     private ScrollView scrollView;
     private TextView logTextView;
    
     private ServiceConnection serviceConnection = new ServiceConnection() {
         @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
             MQTTService.LocalBinder binder = (MQTTService.LocalBinder) service;
             mqttService = binder.getService();
             isBound = true;
    
             // 初始化MQTT管理器
             mqttService.initializeMQTT(
                     "tcp://172.16.1.104:1883",  // 替换为你的MQTT服务器地址
                     "AndroidClient_" + System.currentTimeMillis(),
                     "",  // 用户名(如有需要)
                     ""   // 密码(如有需要)
             );
    
             // 设置回调
             mqttService.getMQTTManager().setCallback(MainActivity.this);
    
             updateUIState();
             appendLog("服务已连接");
         }
    
         @Override
         public void onServiceDisconnected(ComponentName name) {
             isBound = false;
             mqttService = null;
             updateUIState();
             appendLog("服务已断开");
         }
     };
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
    
         mainHandler = new Handler(getMainLooper());
    
         initViews();
         setupListeners();
         bindMQTTService();
     }
    
     private void initViews() {
         connectButton = findViewById(R.id.btn_connect);
         disconnectButton = findViewById(R.id.btn_disconnect);
         subscribeButton = findViewById(R.id.btn_subscribe);
         unsubscribeButton = findViewById(R.id.btn_unsubscribe);
         sendButton = findViewById(R.id.btn_send);
    
         topicEditText = findViewById(R.id.et_topic);
         messageEditText = findViewById(R.id.et_message);
         subscribeTopicEditText = findViewById(R.id.et_subscribe_topic);
    
         scrollView = findViewById(R.id.scroll_view);
         logTextView = findViewById(R.id.tv_log);
    
         // 设置默认值
         topicEditText.setText("test");
         subscribeTopicEditText.setText("test");
         messageEditText.setText("Hello from Android!");
     }
    
     private void setupListeners() {
         connectButton.setOnClickListener(v -> connectToMQTT());
         disconnectButton.setOnClickListener(v -> disconnectFromMQTT());
         subscribeButton.setOnClickListener(v -> subscribeToTopic());
         unsubscribeButton.setOnClickListener(v -> unsubscribeFromTopic());
         sendButton.setOnClickListener(v -> sendMessage());
     }
    
     private void bindMQTTService() {
         Intent intent = new Intent(this, MQTTService.class);
         bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
         startService(intent); // 确保服务启动
     }
    
     private void connectToMQTT() {
         if (isBound && mqttService != null) {
             mqttService.getMQTTManager().connect();
         } else {
             showToast("服务未就绪");
         }
     }
    
     private void disconnectFromMQTT() {
         if (isBound && mqttService != null) {
             mqttService.getMQTTManager().disconnect();
         }
     }
    
     private void subscribeToTopic() {
         String topic = subscribeTopicEditText.getText().toString().trim();
         if (topic.isEmpty()) {
             showToast("请输入主题名称");
             return;
         }
    
         if (isBound && mqttService != null) {
             mqttService.getMQTTManager().subscribe(topic, 1);
         }
     }
    
     private void unsubscribeFromTopic() {
         String topic = subscribeTopicEditText.getText().toString().trim();
         if (topic.isEmpty()) {
             showToast("请输入主题名称");
             return;
         }
    
         if (isBound && mqttService != null) {
             mqttService.getMQTTManager().unsubscribe(topic);
         }
     }
    
     private void sendMessage() {
         String topic = topicEditText.getText().toString().trim();
         String message = messageEditText.getText().toString().trim();
    
         if (topic.isEmpty()) {
             showToast("请输入主题");
             return;
         }
    
         if (message.isEmpty()) {
             showToast("请输入消息内容");
             return;
         }
    
         if (isBound && mqttService != null) {
             mqttService.getMQTTManager().publish(topic, message, 1, false);
             appendLog("发送消息: " + message + " 到主题: " + topic);
         }
     }
    
     private void updateUIState() {
         runOnUiThread(() -> {
             if (isBound && mqttService != null) {
                 boolean connected = mqttService.getMQTTManager().isConnected();
                 connectButton.setEnabled(!connected);
                 disconnectButton.setEnabled(connected);
                 subscribeButton.setEnabled(connected);
                 unsubscribeButton.setEnabled(connected);
                 sendButton.setEnabled(connected);
             } else {
                 connectButton.setEnabled(false);
                 disconnectButton.setEnabled(false);
                 subscribeButton.setEnabled(false);
                 unsubscribeButton.setEnabled(false);
                 sendButton.setEnabled(false);
             }
         });
     }
    
     private void appendLog(String message) {
         mainHandler.post(() -> {
             String timestamp = android.text.format.DateFormat.format("HH:mm:ss", System.currentTimeMillis()).toString();
             String logEntry = "[" + timestamp + "] " + message + "\n";
             logTextView.append(logEntry);
    
             // 自动滚动到底部
             scrollView.fullScroll(View.FOCUS_DOWN);
         });
     }
    
     private void showToast(String message) {
         mainHandler.post(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
     }
    
     @Override
     public void onConnected() {
         appendLog("MQTT已连接");
         updateUIState();
     }
    
     @Override
     public void onDisconnected() {
         appendLog("MQTT已断开");
         updateUIState();
     }
    
     @Override
     public void onMessageReceived(String topic, String message) {
         appendLog("收到消息 - 主题: " + topic + ", 内容: " + message);
     }
    
     @Override
     public void onError(String error) {
         appendLog("错误: " + error);
         showToast(error);
     }
    
     @Override
     protected void onDestroy() {
         if (isBound) {
             unbindService(serviceConnection);
             isBound = false;
         }
         super.onDestroy();
     }

    }

  4. MQTTService.java

    package cn.wx.mqtt;

    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;

    public class MQTTService extends Service {
    private static final String TAG = "MQTTService";
    private final IBinder binder = new LocalBinder();
    private MQTTManager mqttManager;

    复制代码
     public class LocalBinder extends Binder {
         public MQTTService getService() {
             return MQTTService.this;
         }
     }
    
     @Override
     public void onCreate() {
         super.onCreate();
         Log.d(TAG, "MQTT服务创建");
     }
    
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log.d(TAG, "MQTT服务启动");
         return START_STICKY; // 服务被杀死后会自动重启
     }
    
     @Override
     public IBinder onBind(Intent intent) {
         Log.d(TAG, "MQTT服务绑定");
         return binder;
     }
    
     @Override
     public boolean onUnbind(Intent intent) {
         Log.d(TAG, "MQTT服务解绑");
         return super.onUnbind(intent);
     }
    
     @Override
     public void onDestroy() {
         Log.d(TAG, "MQTT服务销毁");
         if (mqttManager != null) {
             mqttManager.cleanup();
         }
         super.onDestroy();
     }
    
     public void initializeMQTT(String serverUri, String clientId, String username, String password) {
         if (mqttManager == null) {
             mqttManager = new MQTTManager(this, serverUri, clientId, username, password);
         }
     }
    
     public MQTTManager getMQTTManager() {
         return mqttManager;
     }

    }

  5. MQTTManager.java

    package cn.wx.mqtt;

    import android.content.Context;
    import android.util.Log;

    import org.eclipse.paho.android.service.MqttAndroidClient;
    import org.eclipse.paho.client.mqttv3.IMqttActionListener;
    import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
    import org.eclipse.paho.client.mqttv3.IMqttToken;
    import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
    import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
    import org.eclipse.paho.client.mqttv3.MqttException;
    import org.eclipse.paho.client.mqttv3.MqttMessage;

    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;

    public class MQTTManager {
    private static final String TAG = "MQTTManager";
    private MqttAndroidClient mqttAndroidClient;
    private String serverUri;
    private String clientId;
    private String username;
    private String password;
    private Context context;
    private MQTTCallback callback;
    private ScheduledExecutorService reconnectExecutor;
    private boolean isConnected = false;
    private boolean isConnecting = false;
    private int reconnectInterval = 5; // 重连间隔(秒)
    private int maxReconnectAttempts = 12*2; // 最大重连次数 暂定两分钟
    private int reconnectAttempts = 0;

    复制代码
     public interface MQTTCallback {
         void onConnected();
         void onDisconnected();
         void onMessageReceived(String topic, String message);
         void onError(String error);
     }
    
     public MQTTManager(Context context, String serverUri, String clientId, String username, String password) {
         this.context = context;
         this.serverUri = serverUri;
         this.clientId = clientId;
         this.username = username;
         this.password = password;
         this.reconnectExecutor = Executors.newSingleThreadScheduledExecutor();
         initClient();
     }
    
     private void initClient() {
         try {
             mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
             mqttAndroidClient.setCallback(new MqttCallbackExtended() {
                 @Override
                 public void connectComplete(boolean reconnect, String serverURI) {
                     Log.d(TAG, "连接完成: " + serverURI);
                     isConnected = true;
                     isConnecting = false;
                     reconnectAttempts = 0;
                     if (callback != null) {
                         callback.onConnected();
                     }
                 }
    
                 @Override
                 public void connectionLost(Throwable cause) {
                     Log.e(TAG, "连接丢失", cause);
                     isConnected = false;
                     isConnecting = false;
                     if (callback != null) {
                         callback.onDisconnected();
                     }
                     attemptReconnect();
                 }
    
                 @Override
                 public void messageArrived(String topic, MqttMessage message) throws Exception {
                     String msg = new String(message.getPayload());
                     Log.d(TAG, "收到消息 - 主题: " + topic + ", 内容: " + msg);
                     if (callback != null) {
                         callback.onMessageReceived(topic, msg);
                     }
                 }
    
                 @Override
                 public void deliveryComplete(IMqttDeliveryToken token) {
                     Log.d(TAG, "消息发送完成");
                 }
             });
         } catch (Exception e) {
             Log.e(TAG, "初始化MQTT客户端失败", e);
             if (callback != null) {
                 callback.onError("初始化MQTT客户端失败: " + e.getMessage());
             }
         }
     }
    
     public void connect() {
         if (isConnected || isConnecting) {
             return;
         }
    
         isConnecting = true;
         try {
             MqttConnectOptions options = new MqttConnectOptions();
             options.setAutomaticReconnect(false); // 我们自己处理重连
             options.setCleanSession(true);
             options.setConnectionTimeout(10);
             options.setKeepAliveInterval(60);
             
             if (username != null && !username.isEmpty()) {
                 options.setUserName(username);
             }
             if (password != null && !password.isEmpty()) {
                 options.setPassword(password.toCharArray());
             }
    
             IMqttToken token = mqttAndroidClient.connect(options);
             token.setActionCallback(new IMqttActionListener() {
                 @Override
                 public void onSuccess(IMqttToken asyncActionToken) {
                     Log.d(TAG, "MQTT连接成功");
                     isConnected = true;
                     isConnecting = false;
                     reconnectAttempts = 0;
                     if (callback != null) {
                         callback.onConnected();
                     }
                 }
    
                 @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                     Log.e(TAG, "MQTT连接失败", exception);
                     isConnected = false;
                     isConnecting = false;
                     if (callback != null) {
                         callback.onError("连接失败: " + exception.getMessage());
                     }
                     attemptReconnect();
                 }
             });
         } catch (MqttException e) {
             Log.e(TAG, "连接MQTT服务器异常", e);
             isConnecting = false;
             if (callback != null) {
                 callback.onError("连接异常: " + e.getMessage());
             }
             attemptReconnect();
         }
     }
    
     private void attemptReconnect() {
         if (reconnectAttempts < maxReconnectAttempts && !isConnected && !isConnecting) {
             reconnectAttempts++;
             Log.d(TAG, "尝试重连 (" + reconnectAttempts + "/" + maxReconnectAttempts + ")");
             reconnectExecutor.schedule(() -> {
                 if (!isConnected) {
                     connect();
                 }
             }, reconnectInterval, TimeUnit.SECONDS);
         } else if (reconnectAttempts >= maxReconnectAttempts) {
             Log.e(TAG, "达到最大重连次数,停止重连");
             if (callback != null) {
                 callback.onError("达到最大重连次数,连接失败");
             }
         }
     }
    
     public void subscribe(String topic, int qos) {
         if (!isConnected) {
             Log.w(TAG, "未连接到MQTT服务器,无法订阅主题");
             return;
         }
    
         try {
             IMqttToken token = mqttAndroidClient.subscribe(topic, qos);
             token.setActionCallback(new IMqttActionListener() {
                 @Override
                 public void onSuccess(IMqttToken asyncActionToken) {
                     Log.d(TAG, "订阅主题成功: " + topic);
                 }
    
                 @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                     Log.e(TAG, "订阅主题失败: " + topic, exception);
                     if (callback != null) {
                         callback.onError("订阅主题失败: " + exception.getMessage());
                     }
                 }
             });
         } catch (MqttException e) {
             Log.e(TAG, "订阅主题异常: " + topic, e);
             if (callback != null) {
                 callback.onError("订阅异常: " + e.getMessage());
             }
         }
     }
    
     public void unsubscribe(String topic) {
         if (!isConnected) {
             Log.w(TAG, "未连接到MQTT服务器,无法取消订阅");
             return;
         }
    
         try {
             IMqttToken token = mqttAndroidClient.unsubscribe(topic);
             token.setActionCallback(new IMqttActionListener() {
                 @Override
                 public void onSuccess(IMqttToken asyncActionToken) {
                     Log.d(TAG, "取消订阅主题成功: " + topic);
                 }
    
                 @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                     Log.e(TAG, "取消订阅主题失败: " + topic, exception);
                     if (callback != null) {
                         callback.onError("取消订阅失败: " + exception.getMessage());
                     }
                 }
             });
         } catch (MqttException e) {
             Log.e(TAG, "取消订阅主题异常: " + topic, e);
             if (callback != null) {
                 callback.onError("取消订阅异常: " + e.getMessage());
             }
         }
     }
    
     public void publish(String topic, String message, int qos, boolean retained) {
         if (!isConnected) {
             Log.w(TAG, "未连接到MQTT服务器,无法发送消息");
             if (callback != null) {
                 callback.onError("未连接到MQTT服务器,无法发送消息");
             }
             return;
         }
    
         try {
             MqttMessage mqttMessage = new MqttMessage();
             mqttMessage.setPayload(message.getBytes());
             mqttMessage.setQos(qos);
             mqttMessage.setRetained(retained);
    
             IMqttToken token = mqttAndroidClient.publish(topic, mqttMessage);
             token.setActionCallback(new IMqttActionListener() {
                 @Override
                 public void onSuccess(IMqttToken asyncActionToken) {
                     Log.d(TAG, "消息发送成功 - 主题: " + topic + ", 内容: " + message);
                 }
    
                 @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                     Log.e(TAG, "消息发送失败", exception);
                     if (callback != null) {
                         callback.onError("消息发送失败: " + exception.getMessage());
                     }
                 }
             });
         } catch (MqttException e) {
             Log.e(TAG, "消息发送异常", e);
             if (callback != null) {
                 callback.onError("消息发送异常: " + e.getMessage());
             }
         }
     }
    
     public void disconnect() {
         try {
             if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
                 IMqttToken token = mqttAndroidClient.disconnect();
                 token.setActionCallback(new IMqttActionListener() {
                     @Override
                     public void onSuccess(IMqttToken asyncActionToken) {
                         Log.d(TAG, "MQTT断开连接成功");
                         isConnected = false;
                         isConnecting = false;
                         if (callback != null) {
                             callback.onDisconnected();
                         }
                     }
    
                     @Override
                     public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                         Log.e(TAG, "MQTT断开连接失败", exception);
                         if (callback != null) {
                             callback.onError("断开连接失败: " + exception.getMessage());
                         }
                     }
                 });
             }
         } catch (MqttException e) {
             Log.e(TAG, "断开MQTT连接异常", e);
             if (callback != null) {
                 callback.onError("断开连接异常: " + e.getMessage());
             }
         }
     }
    
     public void setCallback(MQTTCallback callback) {
         this.callback = callback;
     }
    
     public boolean isConnected() {
         return isConnected;
     }
    
     public void setReconnectInterval(int seconds) {
         this.reconnectInterval = seconds;
     }
    
     public void setMaxReconnectAttempts(int attempts) {
         this.maxReconnectAttempts = attempts;
     }
    
     public void cleanup() {
         if (reconnectExecutor != null && !reconnectExecutor.isShutdown()) {
             reconnectExecutor.shutdown();
         }
         disconnect();
     }

    }

  6. AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    复制代码
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
     <application
         android:allowBackup="true"
         android:dataExtractionRules="@xml/data_extraction_rules"
         android:fullBackupContent="@xml/backup_rules"
         android:icon="@mipmap/ic_launcher"
         android:label="@string/app_name"
         android:roundIcon="@mipmap/ic_launcher_round"
         android:supportsRtl="true"
         android:theme="@style/Theme.Mqtttest">
    
         <activity
             android:name=".MainActivity"
             android:exported="true">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
         <service android:name=".MQTTService"
             android:enabled="true"
             android:exported="false" />
         <service android:name="org.eclipse.paho.android.service.MqttService" />
     </application>
    </manifest>

结束

相关推荐
似霰1 小时前
AIDL Hal 开发笔记7----AIDL HAL 的升级
android·framework·hal
2501_916007475 小时前
跨平台 App 安全,Flutter、RN、Unity、H5 混合应用加固
android·ios·小程序·https·uni-app·iphone·webview
hinewcc6 小时前
Linux电源管理 - wakelocks
android·linux
你怎么知道我是队长6 小时前
win11系统查看设备配置
android·java·javascript
DevangLic6 小时前
【确认是否安装了 C++ 工具】
android·java·c++
2501_916007476 小时前
不越狱如何查看iOS 应用的详细信息及其文件目录结构
android·macos·ios·小程序·uni-app·cocoa·iphone
龚礼鹏6 小时前
图像显示框架十——BufferQueue的工作流程(基于Android 15源码分析)
android
TheNextByte17 小时前
如何将音乐从Android手机传输到电脑 [4 种方法]
android·智能手机·电脑
一起养小猫7 小时前
Flutter for OpenHarmony 实战:贪吃蛇蛇的移动逻辑详解
android·flutter