Android Q 接入 MQTT

Android Q 接入 MQTT

首先在APP 下引入mqtt的库

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'

创建一个MQTT连接的实体类

package com.example.iot.bean;

/**
 * @TODO MQTT 连接实体类
 * @Create by: wjw
 * @Create time: 2020/2/8 11:26
 */
public class MQTTentity {

    //以下请自己配置否则MainActivity中button_login的监听会有问题
    private String host;
    private String userName;
    private String passWord;
    private String[] timeTopic;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String[] getTimeTopic() {
        return timeTopic;
    }

    public void setTimeTopic(String[] timeTopic) {
        this.timeTopic = timeTopic;
    }

    public MQTTentity() {
    }

    public MQTTentity(String host, String userName, String passWord, String[] timeTopic) {
        this.host = host;
        this.userName = userName;
        this.passWord = passWord;
        this.timeTopic = timeTopic;
    }

    @Override
    public String toString() {
        return "MQTTentity{" +
                "host='" + host + '\'' +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", timeTopic='" + timeTopic + '\'' +
                '}';
    }
}

然后在activity中写主逻辑

//我们自己新建的MQTT实体类
    private MQTTentity mqttentity;
    private MqttClient client;
    private MqttConnectOptions options;
    //以下两个声明目的是为了实现MQTT消息在testview刷新
    private ScheduledExecutorService scheduler;
    private Handler handler;

在onCreate方法中

handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 1) {
                    Toast.makeText(MonitorAct.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                } else if (msg.what == 2) {
                    MqttToast.setVisibility(View.GONE);
                    try {
                        client.subscribe(mqttentity.getTimeTopic()); //订阅主题“timeTopic”
                        Toast.makeText(MonitorAct.this, "场景已成功接入服务器", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (msg.what == 3) {
                    MqttToast.setVisibility(View.VISIBLE);
                    Toast.makeText(MonitorAct.this, "接入服务器失败,务必确保网络正常,系统正在重连,请稍后...", Toast.LENGTH_LONG).show();
                }
                return false;
            }
        });

mqtt连接

// MQTT 订阅主题
        String[] topics  = new String[1];
        topics[0] = "/wjw";
        mqttentity = new MQTTentity("tcp://127.0.0.1:1888", "admin", "admin", topics);
     initMQTT(mqttentity);
        startReconnect();
 /**
     * @TODO 获取手机imei
     * @Create by: wjw
     * @Create time: 2020/2/8 11:27
     */
    public static String getIMEI(Context context, int slotId) {
        try {
            TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            Method method = manager.getClass().getMethod("getImei", int.class);
            String imei = (String) method.invoke(manager, slotId);
            return imei;
        } catch (Exception e) {
            return "";
        }
    }

/**
     * @TODO MQTT初始化
     * @Create by: wjw
     * @Create time: 2020/2/8 12:08
     */
    private void initMQTT(MQTTentity mqtTentity) {

        // 获取手机IMEI作为clientId
        String imei = getIMEI(MonitorAct.this, 0);
        // HOST为主机名
        try {
            client = new MqttClient(mqtTentity.getHost(), imei, new MemoryPersistence());
        } catch (MqttException e) {
            e.printStackTrace();
        }
        // MQTT连接设置
        options = new MqttConnectOptions();
        // 设置是否清空session,如果是false则表示服务器保留客户端连接记录
        options.setCleanSession(true);
        // 设置连接的用户名
        options.setUserName(mqtTentity.getUserName());
        // 设置连接的密码
        options.setPassword(mqtTentity.getPassWord().toCharArray());
        // 设置超时时间,单位为秒
        options.setConnectionTimeout(10);
        // 设置会话间心跳时间,单位为秒,服务器每隔1.5*20向客户端发消息确认
        options.setKeepAliveInterval(20);
        // 设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                // 连接丢失后,一般在这里进行重连
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // subscribe后,得到的消息会执行到这里
                Message msg = new Message();
                msg.what = 1;
                msg.obj = message.toString();
                handler.sendMessage(msg);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                // publish后,会执行这里
            }
        });

    }
 /**
     * @TODO MQTT建立连接及重连
     * @Create by: wjw
     * @Create time: 2020/2/8 11:48
     */
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    connect();
                }
            }
        }, 0, 10 * 1000, TimeUnit.MILLISECONDS);
    }
/**
     * @TODO MQTT连接状态鉴别
     * @Create by: wjw
     * @Create time: 2020/2/8 11:51
     */
    private void connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client.connect(options);
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 3;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
@Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            scheduler.shutdown();
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(Android)