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清单文件中添加服务

<service android:name="org.eclipse.paho.android.service.MqttService" /> //自带服务
<service android:name="com.xx.xxx.MQTTService"/> //你的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

  • 1
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android应用程序使用MQTT协议可以实现与远程服务器进行实时通信。MQTT是一种轻量级的发布/订阅消息传输协议,适用于移动设备和物联网应用程序。 以下是使用MQTT协议的一般步骤: 1. 添加MQTT库:首先,您需要MQTT库添加到您的Android项目。常用的MQTT库包括Eclipse Paho和MQTT.fx等。 2. 连接到服务器:使用MQTT库提供的API,创建一个MQTT客户端,并连接到远程MQTT服务器。您需要提供服务器的地址、端口号和连接参数(如用户名、密码等)。 3. 订阅主题:通过订阅主题,您可以接收来自服务器的特定消息。主题可以是任意字符串,可以用于区分不同类型的消息。 4. 发布消息:使用MQTT客户端发布消息到特定主题。您可以将数据发送到服务器,并通过订阅该主题的所有客户端接收。 5. 处理接收到的消息:使用订阅回调函数处理从服务器接收到的消息。您可以在回调函数解析和处理消息,并更新UI或执行其他操作。 以下是一个简单的示例,演示如何在Android应用程序使用MQTT协议: 1. 添加依赖: 在您的项目的build.gradle文件添加以下依赖: ```groovy implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' ``` 2. 连接到服务器: ```java String serverUri = "tcp://mqtt.example.com:1883"; String clientId = "android-client"; MqttClient client = new MqttClient(serverUri, clientId); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("username"); options.setPassword("password".toCharArray()); client.connect(options); ``` 3. 订阅主题: ```java String topic = "mytopic"; client.subscribe(topic, new IMqttMessageListener() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // 处理接收到的消息 String payload = new String(message.getPayload()); Log.d(TAG, "Received message: " + payload); } }); ``` 4. 发布消息: ```java String topic = "mytopic"; String payload = "Hello, MQTT!"; client.publish(topic, payload.getBytes(), 0, false); ``` 通过以上步骤,您可以在Android应用程序使用MQTT协议进行实时通信。请注意,您需要根据实际情况配置和处理连接、订阅和发布操作,并确保在适当的时候释放和关闭MQTT客户端连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值