Giter Site home page Giter Site logo

andmqtt's Introduction

AndMqtt

android mqttclient

在项目级别build.gradle添加:

maven { url "https://repo.eclipse.org/content/repositories/paho-snapshots/" }
maven { url "https://jitpack.io" }

在module级别build.gradle添加:

implementation 'com.github.Rairmmd:AndMqtt:1.0.5'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

如何使用

1、初始化

建议在Application中初始化,避免持有Activity导致内存泄露

AndMqtt.init(this);

2.创建连接对象,设置消息监听

MqttConnect mqttConnect = new MqttConnect();
mqttConnect.setMessageListener(new MqttCallbackExtended() {
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        Log.i("Rair", "(MainActivity.java:29)-connectComplete:->连接完成");
    }

    @Override
    public void connectionLost(Throwable cause) {
        Log.i("Rair", "(MainActivity.java:34)-connectionLost:->连接丢失");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        Log.i("Rair", "(MainActivity.java:39)-messageArrived:->收到的消息");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        Log.i("Rair", "(MainActivity.java:44)-deliveryComplete:->消息已送达");
    }
})

对收到的消息进行处理

3.连接服务器

 AndMqtt.getInstance().connect(mqttConnect.setServer("服务器地址")
                .setPort(端口号), new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("Rair", "(MainActivity.java:51)-onSuccess:->连接成功");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.i("Rair", "(MainActivity.java:56)-onFailure:->连接失败");
            }
        });

也可以直接链式调用

AndMqtt.getInstance().connect(new MqttConnect().setClientId("android")
    .setPort(1884).setAutoReconnect(true)
    .setCleanSession(true).setServer("tcp://119.3.27.191")
    .setTraceCallback(new MqttTraceHandler() {
        @Override
        public void traceDebug(String tag, String message) {

        }

        @Override
        public void traceError(String tag, String message) {

        }

        @Override
        public void traceException(String tag, String message, Exception e) {

        }
    }).setMessageListener(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

        }

        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
    }), new IMqttActionListener() {
    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        Log.i("Rair", "(MainActivity.java:51)-onSuccess:->连接成功");
        subscribe();
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        Log.i("Rair", "(MainActivity.java:56)-onFailure:->连接失败");
    }
});

ClientId用于标识设备,取设备唯一值或和服务器约定。

订阅

AndMqtt.getInstance().subscribe(new MqttSubscribe()
    .setTopic("主题").setQos(0), new IMqttActionListener() {
    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        Log.i("Rair", "(MainActivity.java:63)-onSuccess:->订阅成功");
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        Log.i("Rair", "(MainActivity.java:68)-onFailure:->订阅失败");
    }
});

取消订阅

AndMqtt.getInstance().unSubscribe(new MqttUnSubscribe()
    .setTopic("主题"), new IMqttActionListener() {
    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        Log.i("Rair", "(MainActivity.java:93)-onSuccess:->取消订阅成功");
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        Log.i("Rair", "(MainActivity.java:98)-onFailure:->取消订阅失败");
    }
});

发布

AndMqtt.getInstance().publish(new MqttPublish()
    .setMsg("消息").setQos(0).setTopic("主题"), new IMqttActionListener() {
    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        Log.i("Rair", "(MainActivity.java:79)-onSuccess:->发布成功");
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        Log.i("Rair", "(MainActivity.java:84)-onFailure:->发布失败");
    }
});

断开连接

AndMqtt.getInstance().disConnect();

是否连接

boolean isConnect = AndMqtt.getInstance().isConnect();

注意 进行任何操作前都需保证MQTT是连接的
可先用isConnect()判断一下

andmqtt's People

Contributors

reathin avatar

Stargazers

 avatar Oops avatar  avatar Laurensius Dede Suhardiman avatar  avatar zoom avatar  avatar 张杰博 avatar  avatar  avatar  avatar Allen avatar DannyZhou avatar

Watchers

James Cloos avatar

andmqtt's Issues

接受数据的监听有问题

在application中注册 MessageListener监听,无法监听到 其他界面subscribe的数据。 怀疑是上下文生命周期引起的问题。

android.os.BinderProxy cannot be cast to org.eclipse.paho.android.service.MqttServiceBinder

java.lang.ClassCastException: android.os.BinderProxy cannot be cast to org.eclipse.paho.android.service.MqttServiceBinder at org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection.onServiceConnected(MqttAndroidClient.java:111) at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1943) at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1975) at android.os.Handler.handleCallback(Handler.java:891) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:7470) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)

感觉是android:process=":andmqtt"的问题 导致不同进程了。我跑demo时没问题的
<service android:name="org.eclipse.paho.android.service.MqttService" android:enabled="true" android:exported="true" android:process=":andmqtt" />

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.