ESA2GJK1DH1K基础篇: Android连接MQTT简单的Demo

2019-11-12 22:12:34 浏览数 (1)

前言

  这节让大家知道Android是怎么连接的MQTT

  使用的是下面这个包

  官方下载地址

https://docs.emqx.io/sdk_tools?category=MQTT_Clients

新建工程,导入jar包

jar包拷贝到新工程的app/libs目录

软件设置加载jar包

连接MQTT

代码语言:javascript复制
public class MainActivity extends AppCompatActivity {

    private static MqttClient mqttClient;
    private static MqttConnectOptions mqttConnectOptions;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mqttConnectOptions  = new MqttConnectOptions();//MQTT的连接设置
        mqttConnectOptions.setCleanSession(true);//清除连接信息
        mqttConnectOptions.setUserName("yang");//设置连接的用户名
        mqttConnectOptions.setPassword("11223344".toCharArray());//设置连接的密码
        mqttConnectOptions.setConnectionTimeout(3);// 设置连接超时时间 单位为秒
        mqttConnectOptions.setKeepAliveInterval(60);//心跳包时间60S
        try { mqttClient = new MqttClient(
                    "tcp://47.92.31.46:1883",//连接的地址信息
                    System.currentTimeMillis() "",//ClientID,使用当前时间戳
                    new MemoryPersistence());//
            mqttClient.setCallback(new MqttCallback() {//回调函数
                @Override//连接断开
                public void connectionLost(Throwable throwable) { }
                @Override//接收到消息
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception { }
                @Override//没用过
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { }
            });
            new Thread(new Runnable() {//用任务
                @Override
                public void run() {
                    try {
                        mqttClient.connect(mqttConnectOptions);
                        if (mqttClient.isConnected()) {
                            Log.e("Mqtt Info", "ConnectSuccess");
                        }
                    }catch (Exception e){
                        Log.e("Mqtt Err", e.toString());
                    }
                }
            }).start();
        }
        catch (Exception e){
            Log.e("Mqtt Err", e.toString());
        }
    }
}

添加网络通信权限

代码语言:javascript复制
<uses-permission android:name="android.permission.INTERNET" />

下载到手机测试

订阅主题,打印接收的消息

代码语言:javascript复制
Log.e("MqttMsg:", "Topic:" s " " "Msg:" mqttMessage.toString());
代码语言:javascript复制
mqttClient.subscribe("1111",0);//订阅1111,消息等级0

测试

发送消息

代码语言:javascript复制
final MqttMessage msgMessage = new MqttMessage(mqttMessage.toString().getBytes());
new Thread(new Runnable() {//用任务
    @Override
    public void run() {
        try {
            mqttClient.publish("2222",msgMessage);//发布主题为2222的消息
        }catch (Exception e){
            Log.e("Mqtt Err", e.toString());
        }
    }
}).start();

测试

0 人点赞