基于MQTT的安卓开发

制作一个简易的基于MQTT协议开发的安卓调试助手

由于考研的缘故,很久没有做项目了,最近这几天忙着毕设,用了三天去踩了不少坑,分享一下。

1、Android Studio 导入MQTT库

网上导入MQTT库大致有两种办法

第一种办法:MQTT库文件放入项目的根目录中

MQTT库在GitHub的地址:https://github.com/eclipse/paho.mqtt.android.git
再相对应的加入权限和配置。

第二种办法:把一个.jar文件放入app/lib文件中,并且把他加入library中

MQTT库的官方地址:https://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/org.eclipse.paho.client.mqttv3/
把下载后的文件放在app/lib文件下面,然后再右击最后的第二个,把.jar文件添加到library中。

2、IMqttActionListener函数问题

该函数主要是监听函数是否成功或者失败,可是不知道为什么每次用了都会出现这种报错,所以我最后解决不了就选择放弃这个函数了,也许是我太菜了,在网上了愣是找不到什么解决办法,有大佬会的麻烦评论区解决一下。
在这里插入图片描述

3、安卓和MQTT的API文档

MQTT的API文档:https://www.eclipse.org/paho/files/javadoc/org/eclipse/paho/client/mqttv3/MqttClient.html
这个主要是哪个函数不会,就去搜哪个函数,一般百度可以找到这个文档。
安卓的API文档在网上可以搜得到不过个人感觉有点不齐全,最好还是自己去查看JAVA的API文档,那个还是比较全面的。

4、订阅不了的问题(没办法进入messageArrived函数)

这个应该很少人会犯这样的错误,因为我用的不是自己的服务器,所以也就没有设置用户名和用户密码,这也是导致无法进入这个函数的主要原因,也是一直订阅不了的原因。解决的办法就是用户名和密码不能为空。

5、发布一次消息就断开连接的问题

在调试过程中遇到一个问题,当app发布一次消息后就无法再发送一次消息了,看了日志才知道原来MQTT的连接也断开了,我也写过一个重连函数放在里面也没有办法,最后把调试用的代码(如下)注释掉就可以解决了。

System.out.println("connectionLost----------");

6、MainActivity.java

package com.example.great_xiebm.myapplication0;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;



import android.os.Handler;
import android.os.Message;


import android.util.Log;
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.ScheduledExecutorService;



public class MainActivity extends ActionBarActivity {
    public String TAG="MyTAG";
    //private String host = "tcp://内网ip:服务器端口号";

    private String mytopic="hellowllow";

    private Button dingyue1,fabu1,lianjie1;
    private EditText ip1,port1,use1,password1,fubutopic1,fubuneirong1,dingyuetopic1;
    private TextView message1;

    private  String ip,port,uname,psd,pubulishneirong,fubutopic2,dingyuetopic2;
    private StringBuffer messageData=new StringBuffer();

    private String clientId="123";
    private MqttClient client;
    private MqttConnectOptions options;
    public Handler handler;
    private ScheduledExecutorService scheduler;





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


        dingyue1= (Button) findViewById(R.id.subscribe); //定义按钮
        fabu1= (Button) findViewById(R.id.publish);
        lianjie1= (Button) findViewById(R.id.cancel);

        ip1= (EditText) findViewById(R.id.ip); //定义EDitText窗口
        port1= (EditText) findViewById(R.id.port);
        use1= (EditText) findViewById(R.id.user);
        password1= (EditText) findViewById(R.id.password);
        fubutopic1= (EditText) findViewById(R.id.fubutopic);
        fubuneirong1= (EditText) findViewById(R.id.fubuneirong);
        dingyuetopic1= (EditText) findViewById(R.id.dingyuetopic);

        message1= (TextView) findViewById(R.id.message); //定义接收到的消息


        lianjie1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connect();


            }
        });
        fabu1.setOnClickListener(new View.OnClickListener(){   //发布按钮设置
            @Override
            public void onClick(View v){
                pubulishneirong=fubuneirong1.getText().toString().trim();

                publish(pubulishneirong);

            }
        });

        dingyue1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                subscrible();
            }
        });




        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();

                }else if(msg.what==2){
                    Toast.makeText(MainActivity.this,"fail",Toast.LENGTH_SHORT).show();

                }else if(msg.what==3){
                    Toast.makeText(MainActivity.this,(String)msg.obj,Toast.LENGTH_SHORT).show();
                    message1.setText((String) msg.obj);
                }

            }
        };
    }

    private void connect()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                init();
                try {
                    client.connect(options);
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);//连接成功

                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                    //连接失败
                }

            }
        }).start();
    }

    
    private void init() {
        try {

            ip=ip1.getText().toString().trim();
            port=port1.getText().toString().trim();
            uname=use1.getText().toString().trim();
            psd=password1.getText().toString().trim();

            client=new MqttClient("tcp://"+ip+":"+port,clientId,new MemoryPersistence());

            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(uname);
            //设置连接的密码
            options.setPassword(psd.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
//                    System.out.println("connectionLost----------");
                      Toast.makeText(MainActivity.this,"connectionLost----------",Toast.LENGTH_SHORT).show();
                }
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage){
                    System.out.println("messageArrived----------");
                    String str1 = new String(mqttMessage.getPayload());
                    Log.d(TAG, "messageArrived: " + str1);
                    Message msg=new Message();
                    msg.what=3;
                    msg.obj=str1;
                    handler.sendMessage(msg);

                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    Toast.makeText(MainActivity.this,"deliveryComplete---------",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void publish(String msg){

        fubutopic2=fubutopic1.getText().toString().trim();
        Integer qos = 0;
        Boolean retained = false;
        try {
            client.publish(fubutopic2, msg.getBytes(), qos.intValue(), retained.booleanValue());
            Toast.makeText(MainActivity.this,"发布成功",Toast.LENGTH_LONG).show();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    public  void subscrible(){
        dingyuetopic2=dingyuetopic1.getText().toString().trim();

        try {
            client.subscribe(dingyuetopic2,0);

            message1.setText("订阅成功");
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            scheduler.shutdown();
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}


7、成果

在这里插入图片描述
在这里插入图片描述

7、完整APP

https://download.csdn.net/download/weixin_43262746/12331291

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值