0

我按照一些教程来了解如何从 Android 设备publish发送消息。broker下面是我的尝试,此时,我没有找到教程中提供的方法,就像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();
4

1 回答 1

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());

            }
        });
于 2015-04-24T09:51:17.920 回答