安卓写Mqtt(java)

news/2024/5/20 2:34:12 标签: android, gradle, java

前置

  1. setting.gradle里面添加

    java">maven { url ‘https://jitpack.io’ }
    maven { url ‘https://repo.eclipse.org/content/repositories/paho-releases/}
    
    java">pluginManagement {
        repositories {
            gradlePluginPortal()
            google()
            mavenCentral()
        }
    }
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            google()
            mavenCentral()
            maven { url 'https://jitpack.io' }
            maven { url 'https://repo.eclipse.org/content/repositories/paho-releases/'}
        }
    }
    rootProject.name = "My Application"
    include ':app'
    
  2. 添加库

    java">implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
    
  3. 添加服务

    java"><service android:name="org.eclipse.paho.android.service.MqttService" /> //自带服务
    

代码

main

java">    package com.example.myapplication;
    import androidx.appcompat.app.AppCompatActivity;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
    import org.eclipse.paho.client.mqttv3.MqttCallback;
    import org.eclipse.paho.client.mqttv3.MqttClient;
    import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
    import org.eclipse.paho.client.mqttv3.MqttException;
    import org.eclipse.paho.client.mqttv3.MqttMessage;
    import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
    import org.json.JSONObject;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;

    public class MainActivity extends Activity {


     private Handler handler;
     private MqttClient client;
     private MqttConnectOptions options;
     private ScheduledExecutorService scheduler;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         EditText publishTopic = findViewById(R.id.publish_topic);
         EditText subscribeTopic = findViewById(R.id.subscribe_topic);
         EditText publishMessage = findViewById(R.id.publish_content);
         EditText subscribeMessage = findViewById(R.id.subscribe_content);
         Button connectServer = findViewById(R.id.connectServer);
         Button publishButton = findViewById(R.id.publish);
         Button subscribeButton = findViewById(R.id.subscribe);

         MqttUtils mqttUtils = new MqttUtils();
         mqttUtils.subscribeMsgEdit = subscribeMessage;
         connectServer.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 mqttUtils.init();
                 mqttUtils.Mqtt_connect();
             }
         });

         publishButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 String topic = publishTopic.getText().toString();
                 String message = publishMessage.getText().toString();
                 mqttUtils.mqtt_pub_topic = topic;
                 mqttUtils.publishmessageplus(message);
             }
         });

         subscribeButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 mqttUtils.mqtt_sub_topic= subscribeTopic.getText().toString();
                 mqttUtils.sub();

             }
         });


     }


 }

util

java">package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

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


public class MqttUtils  {

    MqttUtils(){
        this.host = "tcp://47.109.46.65:1883";
        this.mqtt_id = "kafens_phone";
        this.userName = "kafen";
        this.passWord = "kafen";

    }

    public String host ;
    public String mqtt_id ;
    public String userName ;
    public String passWord ;
    public MqttClient client;
    public String mqtt_sub_topic = "my_sub";
    public String mqtt_pub_topic ="my_pub";
    public String subscribeMsg;
    public MqttConnectOptions options;
    public ScheduledExecutorService scheduler;
    public EditText subscribeMsgEdit;


    public void init() {
        try {
            client = new MqttClient(host, mqtt_id, new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost----------");
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message) {
                    subscribeMsg =  message.toString();
                    handler.sendEmptyMessage(3);

                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }



    Handler handler = new Handler() {

        @SuppressLint("SetTextIl8n")
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: //开机校验更新回传
                    break;
                case 2: //反馈回转
                    break;
                case 3: //MQTT收到消息回传
                    subscribeMsgEdit.setText(subscribeMsg);
                    break;

                case 30: //连接失败
                     // Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
                    System.out.println("connect failed");
                    break;
                case 31: //连接成功
                    // Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();

                    break;
                case 92:
                    try {
                        client.subscribe(mqtt_sub_topic, 2);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    public void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!( client.isConnected())){
                        client.connect(options);
                        Message msg = new Message();
                        msg.what=31;

                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();

    }


    public void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }


    public void publishmessageplus(String message2)
    {
        if (client == null || !client.isConnected()){
           return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(mqtt_pub_topic,message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


public  void sub()  {
    try {
        client.subscribe(mqtt_sub_topic, 2);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}




}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/publish_topic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Topic to publish"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/publish_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input things to published"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/subscribe_topic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Topic to subscribe "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/subscribe_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="This is what you will be received "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/connectServer"
        android:text="Connect to Server"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/subscribe"
        android:text="Subscribe"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/publish"
        android:text="Publish"/>







</LinearLayout>

工程下载

gitee下载


http://www.niftyadmin.cn/n/1689138.html

相关文章

安卓库-图表库: MPChartView

依赖设置 略 绘制柱状图 <?xml version"1.0" encoding"utf-8"?> <RelativeLayoutxmlns:android"http://schemas.android.com/apk/res/android"xmlns:app"http://schemas.android.com/apk/res-auto"xmlns:tools"htt…

STM32(X) SD卡协议详解

SPI读写字节 u8 SPI1_ReadWriteByte(u8 TxData)//读写 { u8 retry0; while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) RESET) //发送是否完成{retry;if(retry>200)return 0;} SPI_I2S_SendData(SPI1, TxData); //当发送完成之后才继续发送retry0;while (…

FATFS解读(X):字符串函数

/*-----------------------------------------------------------------------*/ /* 字符串函数 */ /*-----------------------------------------------------------------------*///内存间复制 //输入参数 //1. 目的内…

FATFS(X):读写多字节(字)

/*-----------------------------------------------------------------------*/ /* 在 FAT结构中 写/读 多字节字*/ /*-----------------------------------------------------------------------*///写字&#xff08;低位优先&#xff09; static WORD l…

mysql函数和约束

其余的函数仿照。 其余的类似、 和上面相同 约束

重邮SYDTEK实习(一): 4k和BLE profile烧录

前序准备 项目工具开发板主控SYD 8811代码IDEKeil4K以及profile烧录工具SYDTEK Studio调试工具Jlink sydtek studio使用注意 连接USB 烧录4K文件 烧录BLE profle文件 Keil使用注意 文件路径需要全英文 需要预先写入flash配置 系统环境中的TEMP和TMP路径需要全英文 …

环境搭建:Qt

声明&#xff1a;使用Qt 5.9.0 进行配置 构建套件Kit配置 组件说明MSVC微软的VC运行库MinGWWindows平台的GNU组件UWPWindows平台的MSVC生成的Qt库Android安卓开发 2. 重新配置Kit的临时仓库 https://mirrors.ustc.edu.cn/qtproject/online/qtsdkrepository/windows_x86/root…

外接键盘win键无效

游戏键盘厂商为了防止误触会设计给win键上锁&#xff0c;按fnwin会解锁&#xff0c;解开就ok了。