[英]Regarding publishing a message using aho Android API
I followed some tutorial to know how to publish
a message to the broker
from Android device. 我遵循了一些教程,以了解如何从Android设备向broker
publish
消息。 Below is my attempt, and at this point, I did not find the methods provided in the tutorial like MqttDeliveryTokenAndroid
it is not in the library. 下面是我的尝试,目前,我没有找到本教程中提供的方法,例如MqttDeliveryTokenAndroid
它不在库中。
Please let me know how to publish
a message correctly AND please provide a link to the recently updated Paho Android API, the one I am working on now is downloaded from Paho
website and some classes and methods and the one I mentioned above are missing. 请让我知道如何正确publish
消息,并提供指向最近更新的Paho Android API的链接,我现在正在使用的一个是从Paho
网站下载的, Paho
一些类和方法以及我上面提到的那个。
Code 码
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();
The NullPointerException is because connect() calls an asynchronous method and you need to implement an ActionListener . NullPointerException是因为connect()调用异步方法,并且您需要实现ActionListener 。
In case of success you could subscribe and publish messages. 如果成功,您可以订阅和发布消息。
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());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.