I followed some tutorial to know how to publish
a message to the broker
from Android device. 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.
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.
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 .
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());
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.