settings.gradle
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
}
rootProject.name = "MQTTTest"
include ':app'
build.gradle (:app)
.....
dependencies {
......
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.greenrobot:eventbus:3.3.1'
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnConnect"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:text="Connect"
app:layout_constraintBottom_toTopOf="@+id/btnPublish"
tools:layout_editor_absoluteX="0dp" />
<Button
android:id="@+id/btnPublish"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:text="Publish"
app:layout_constraintBottom_toTopOf="@+id/btnSubscribe"
tools:layout_editor_absoluteX="0dp" />
<Button
android:id="@+id/btnSubscribe"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:text="Subscribe"
app:layout_constraintBottom_toTopOf="@+id/textmqttmessage"
tools:layout_editor_absoluteX="0dp" />
<TextView
android:id="@+id/textmqttmessage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:text="MQTT Message"
app:layout_constraintBottom_toTopOf="@+id/btndisConnect"
tools:layout_editor_absoluteX="0dp" />
<Button
android:id="@+id/btndisConnect"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="52dp"
android:text="Disconnect"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteX="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package itts.onno.mqtttest;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
public class MainActivity extends AppCompatActivity {
public static final String URL = "tcp://192.168.0.7:1883";
// private String userName = "userName";
// private String password = "password";
// private String clientId = "clientId";
private String userName = "onno";
private String password = "123456";
private String clientId = "MQTTTest";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textmqttmessage);
textView.setText("MQTT Message masuk"); //set text for text view
findViewById(R.id.btnConnect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
boolean b = MqttManager.getInstance().creatConnect(URL, userName, password, clientId);
// Logger.d("isConnected: " + b);
// EventBus.getDefault().register( this );
}
}).start();
}
});
findViewById(R.id.btnPublish).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
MqttManager.getInstance().publish("demo", 2, "MQTT Android Test".getBytes());
}
}).start();
}
});
findViewById(R.id.btnSubscribe).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
MqttManager.getInstance().subscribe("demo", 2);
// EventBus.getDefault().register( this );
}
}).start();
}
});
findViewById(R.id.btndisConnect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
MqttManager.getInstance().disConnect();
// EventBus.getDefault().unregister( this );
} catch (MqttException e) {
}
}
}).start();
}
});
EventBus.getDefault().register(this);
}
/**
* Subscribe to received messages
* The Event type here can be customized as needed, here is only a basic demonstration
*
* @param message
*/
@Subscribe
public void onEvent(MqttMessage message) {
// Logger.d(message.toString());
// Toast.makeText(this, message.toString() ,Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.textmqttmessage);
textView.setText( message.toString() ); //set MQTT message as text
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
MqttManager.java
package itts.onno.mqtttest;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
class MqttManager {
// instance
private static MqttManager mInstance = null;
// Private instance variables
private MqttClient client;
private MqttConnectOptions conOpt;
private boolean clean = true;
// callback
private MqttCallback mCallback;
private MqttManager() {
mCallback = new MqttCallbackBus();
}
public static MqttManager getInstance() {
if (null == mInstance) {
mInstance = new MqttManager();
}
return mInstance;
}
/**
* Release the instance, and the resources it references
*/
public static void release() {
try {
if (mInstance != null) {
mInstance.disConnect();
mInstance = null;
}
} catch (Exception e) {
}
}
/**
* Create Mqtt connection
*
* @param brokerUrl (tcp://xxxxxx:1883)
* @param userName
* @param password
* @param clientId clientId
* @return
*/
public boolean creatConnect(String brokerUrl, String userName, String password, String clientId) {
boolean flag = false;
String tmpDir = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
try {
// Construct the connection options object that contains connection parameters
// such as cleanSession and LWT
conOpt = new MqttConnectOptions();
conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
conOpt.setCleanSession(clean);
if (password != null) {
conOpt.setPassword(password.toCharArray());
}
if (userName != null) {
conOpt.setUserName(userName);
}
// Construct an MQTT blocking mode client
client = new MqttClient(brokerUrl, clientId, dataStore);
// Set this wrapper as the callback handler
client.setCallback(mCallback);
flag = doConnect();
} catch (MqttException e) {
Logger.e(e.getMessage());
}
return flag;
}
/**
* establish connection
*
* @return
*/
public boolean doConnect() {
boolean flag = false;
if (client != null) {
try {
client.connect(conOpt);
// Logger.d("Connected to " + client.getServerURI() + " with client ID " + client.getClientId());
flag = true;
} catch (Exception e) {
}
}
return flag;
}
/**
* Publish / send a message to an MQTT server
*
* @param topicName the name of the topic to publish to
* @param qos the quality of service to delivery the message at (0,1,2)
* @param payload the set of bytes to send to the MQTT server
* @return boolean
*/
public boolean publish(String topicName, int qos, byte[] payload) {
boolean flag = false;
if (client != null && client.isConnected()) {
// Logger.d("Publishing to topic \"" + topicName + "\" qos " + qos);
// Create and configure a message
MqttMessage message = new MqttMessage(payload);
message.setQos(qos);
// Send the message to the server, control is not returned until
// it has been delivered to the server meeting the specified
// quality of service.
try {
client.publish(topicName, message);
flag = true;
} catch (MqttException e) {
}
}
return flag;
}
/**
* Subscribe to a topic on an MQTT server
* Once subscribed this method waits for the messages to arrive from the server
* that match the subscription. It continues listening for messages until the enter key is
* pressed.
*
* @param topicName to subscribe to (can be wild carded)
* @param qos the maximum quality of service to receive messages at for this subscription
* @return boolean
*/
public boolean subscribe(String topicName, int qos) {
boolean flag = false;
if (client != null && client.isConnected()) {
// Subscribe to the requested topic
// The QoS specified is the maximum level that messages will be sent to the client at.
// For instance if QoS 1 is specified, any messages originally published at QoS 2 will
// be downgraded to 1 when delivering to the client but messages published at 1 and 0
// will be received at the same level they were published at.
// Logger.d("Subscribing to topic \"" + topicName + "\" qos " + qos);
try {
client.subscribe(topicName, qos);
flag = true;
} catch (MqttException e) {
}
}
return flag;
}
/**
* disconnect the connection
*
* @throws MqttException
*/
public void disConnect() throws MqttException {
if (client != null && client.isConnected()) {
client.disconnect();
}
}
}