Android Studio MQTT功能

萧丁雨
2023-12-01

使用的Android Studio版本为3.0.1,没办法,升级到3.2.1后弄不出来了,又下了个3.0的绿色版,反正自己用又不考虑用户感受啥的,能实现我想要的功能能在我手机上跑就OK。
首先是APP下build.grdle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.example.administrator.kongzhiqi"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
    compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.orhanobut:logger:2.1.1'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    testCompile 'junit:junit:4.12'
}

然后是项目下的build.grdle文件

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

最后在AndroidManifest.xml中加入权限:

<!-- 运行权限 -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

注册服务(呢吗,在3.2版本中死活注册不了):

<!-- Mqtt 服务 -->
        <service android:name="org.eclipse.paho.android.service.MqttService" />

接下来就可以写逻辑代码了,先定义mqtt要用到的配置参数

    private String topic = "订阅主题";
    private String user = "用户名";
    private String pass = "密码";
    private String host = "mqtt服务器地址,tcp://xxx:1883";
    private String clientId = "发送消息的ID";
    private String clientId1 = "接收消息的ID,不要与发送ID一样";
    private int qos = 0; //消息等级

建立MQTT连接发送消息

                //消息缓存方式,内存缓存
                MemoryPersistence persistence = new MemoryPersistence ();
                 try {
                    //建立客户端
                    MqttClient sampleClient = new MqttClient (broke,clientId,persistence);
                    //连接的配置参数
                    MqttConnectOptions connectOptions = new MqttConnectOptions ();
                    connectOptions.setCleanSession (true);  //不记忆上次会话
                    connectOptions.setUserName (user); //用户名
                    connectOptions.setPassword (pass.toCharArray ()); //密码
                    connectOptions.setConnectionTimeout(30);  //超时时间
                    connectOptions.setKeepAliveInterval(60); //心跳时间,单位秒
                    connectOptions.setAutomaticReconnect(true);//自动重连
                    System.out.println ("connecting to broker" );
                    //连接服务器
                    sampleClient.connect (connectOptions);
                    //用Gson框架建立要发送的json字符串
                    esp8266 a1 = new esp8266("0001", "01", "qidong");
                   Gson gson = new Gson();
                   String json = gson.toJson(a1);
                    //创建消息
                    MqttMessage message = new MqttMessage (json.getBytes ());
                    //设定消息发送等级
                    message1.setQos (qos);
                    //发布消息
                    sampleClient.publish (topic,message);
                    //断开连接
                    sampleClient.disconnect ();
                   // System.exit (0);//关闭UI进程
                } catch (MqttException e) {
                    e.printStackTrace ();
                }

MQTT接受消息

         //消息缓存方式,内存缓存
          MemoryPersistence persistence = new MemoryPersistence ();
         //clientId1 参数不能与发信端一样
         MqttAndroidClient androidClient = new MqttAndroidClient(getApplicationContext(), host, clientId1, persistence);
          //连接的配置参数
          MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setUserName(user);
        options.setPassword(pass.toCharArray());
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(60);
        try {
            //这个代码启动后一直运行
            androidClient.connect(options);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        androidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                //连接成功
                subscribeToTopic();
            }

            @Override
            public void connectionLost(Throwable cause) {
                 //连接中断
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
               //消息到达
                startNotification(message);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                 //接收完成
            }
        });
    }
    private void subscribeToTopic() {
        try {
            androidClient.subscribe("topic", qos, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    //成功收到消息
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                       //接收消息失败
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

     private void startNotification(MqttMessage message) {
        //收到的信息
        String info = message.toString();
        //把json字符串转为java对象
        Gson gson = new Gson();
        esp8266_shou a2 = gson.fromJson(info, esp8266_shou.class);
       //这里就写收到信息的业务逻辑
    }

这个代码能在8.0系统上跑,写了个控制8266的APP,先就这样把,等双11买的继电器模块和oled屏到了在折腾下,其实,本来是打算集成一下百度的语音控制的,那代码有的看不懂,代码又多,暂时打退堂鼓了,等闲得无聊的时候在试试。先把弄了的写在这里记着,方便以后自己查找。再次说明,偶是菜鸟,偶是菜鸟,偶是菜鸟!!!

 类似资料: