关于使用aho Android API发布消息

时间:2014-11-17 10:26:27

标签: android mqtt messagebroker paho

我按照一些教程了解如何从Android设备publishbroker发送消息。下面是我的尝试,此时,我没有找到教程中提供的方法,如MqttDeliveryTokenAndroid它不在库中。

请告诉我如何正确publish邮件,并提供最近更新的Paho Android API的链接,我现在正在处理的那个API是从Paho网站和某些课程下载的方法和我上面提到的方法都不见了。

代码

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mqtt_proj_01_layout);

    sdCard = Environment.getExternalStorageDirectory();
    folder = new File(sdCard + directory);
    if (!folder.exists())
        folder.mkdir();

    final MqttClientPersistence persistenceDataDir = new MqttDefaultFilePersistence(folder.toString());

    final MqttAndroidClient client_1 = new MqttAndroidClient(getApplicationContext(), serverURI,   
    clientID, persistenceDataDir, Ack.AUTO_ACK);
    MqttConnectOptions opts = new MqttConnectOptions();
    opts.setCleanSession(false);
    opts.setWill(WILL_TOPIC, WILL_MSG.getBytes(), 1, true);
    opts.setKeepAliveInterval(keepAliveInterval);

    final MqttMessage msg = new MqttMessage("33".getBytes());
    msg.setQos(1);
    msg.setRetained(false);

    MqttDeliveryToken deliveryToken = new MqttDeliveryToken();

1 个答案:

答案 0 :(得分:0)

NullPointerException 是因为connect()调用异步方法,您需要实现 ActionListener

如果成功,您可以订阅发布消息。

Log.i(LOGTAG, "MQTT Start");
    MemoryPersistence memPer = new MemoryPersistence();
    final MqttAndroidClient client = new MqttAndroidClient(context, "tcp://192.168.0.13:1883", username, memPer);

    try {
        client.connect(null, new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken mqttToken) {
                Log.i(LOGTAG, "Client connected");
                Log.i(LOGTAG, "Topics="+mqttToken.getTopics());

                MqttMessage message = new MqttMessage("Hello, I am Android Mqtt Client.".getBytes());
                message.setQos(2);
                message.setRetained(false);

                try {
                    client.publish("messages", message);

                    Log.i(LOGTAG, "Message published");

                    client.disconnect();
                    Log.i(LOGTAG, "client disconnected");
                } catch (MqttPersistenceException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(IMqttToken arg0, Throwable arg1) {
                // TODO Auto-generated method stub
                Log.i(LOGTAG, "Client connection failed: "+arg1.getMessage());

            }
        });