Android中简单使用MQTT

一、什么是MQTT

MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 20922)下基于发布/订阅范式的消息协议。它工作在TCP/IP协议族上,是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议-----------百度百科
作为一名Android工程师确实很少接触到这类通行协议方式,大多数都是第三方封装好了的工具供调用,比如消息推送什么的多数是基于MQTT,所以这里补一波

二、如何集成

1.添加mave仓库URL
maven { url ‘https://repo.eclipse.org/content/repositories/paho-releases/’}
如果已经有maven地址了,则另起一行添加
是这样的哦
maven { url ‘https://jitpack.io’ }
maven { url ‘https://repo.eclipse.org/content/repositories/paho-releases/’}

2.添加implementation
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.在Manifest清单文件中添加服务

 //自带服务
 //你的MQTT服务

这样你的集成就算完成啦,下面开始编码

三、MQTT服务代码编写

我这儿就直接放代码了

public class MQTTService extends Service implements MqttCallback {

    private static final String HOST = "tcp://19.168.1.1:1883";
    private static final String USERNAME = "user";
    private static final String PSD = "123456";
    private static MqttAndroidClient androidClient;
    private MqttConnectOptions connectOptions;
    private static final String TOPIC = "订阅话题";
    private static final String CLIENTID = "123456789";
    private static final int QOS = 0;	//传输质量

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        androidClient = new MqttAndroidClient(this,HOST,CLIENTID);
        androidClient.setCallback(this);
        connectOptions = new MqttConnectOptions();
        connectOptions.setCleanSession(true);
        connectOptions.setConnectionTimeout(10);
        connectOptions.setKeepAliveInterval(20);
        connectOptions.setUserName(USERNAME);
        connectOptions.setPassword(PSD.toCharArray());
        //设置最后的遗嘱
        boolean doConnect = true;
        String message =  "{\"terminal_uid\":\"" + CLIENTID + "\"}";
        if(!message.equals("")){
            connectOptions.setWill(TOPIC,message.getBytes(),QOS,true);
        }
        if(doConnect){
            doClientConnection();
        }

    }

    //发送消息
    public void sendMessage(String message){
        if(androidClient != null && androidClient.isConnected()){
            try {
                androidClient.publish(TOPIC,message.getBytes(),QOS,true);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }else {
            doClientConnection();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new CustomBinder();
    }

    @Override
    public void onDestroy() {
        if(androidClient != null){
            try {
                androidClient.disconnect();
                androidClient.unregisterResources();
                androidClient.close();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    private void doClientConnection() {
        if(!androidClient.isConnected()){
            try {
                androidClient.connect(connectOptions,null,iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            //连接成功
            LogUtils.e("MQTT","---->connection success");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            //连接失败
            LogUtils.e("MQTT","---->connection failure"+exception.toString());
            doClientConnection();
        }
    };

    public class CustomBinder extends Binder{
        public MQTTService getService(){
            return MQTTService.this;
        }
    }


    /**
     * 连接并监听消息
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        LogUtils.e("MQTT","---->connectionLost:"+cause.toString());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String getMessage = new String(message.getPayload());
        LogUtils.e("MQTT","---->Message:"+getMessage);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}

主体就这样了写的简单

public class MQTTServiceConnction implements ServiceConnection {

    private MQTTService mqttService;
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MQTTService.CustomBinder binder = (MQTTService.CustomBinder) service;
        mqttService = binder.getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    public MQTTService getMqttService(){
        if(mqttService != null){
            return mqttService;
        }
        return null;
    }
}

下面就是在Activity中绑定服务和解绑服务了
绑定服务

MQTTServiceConnction mqttServiceConnction = new MQTTServiceConnction();
Intent intent = new Intent(this,MQTTService.class);
.....
.....
//信息发送
mqttServiceConnction.getMqttService().sendMessage(“要发送的信息”);

在onDestory()中解绑服务就搞完了

unbindService(mqttServiceConnction);

四、相关参考网站

1.官网:http://mqtt.org/
2.MQTT Android API: http://www.eclipse.org/paho/files/android-javadoc/index.html

你可能感兴趣的:(Android杂谈,android,mqtt)