Difference between revisions of "MQTT: Android Studio MQTT Test"
Jump to navigation
Jump to search
Onnowpurbo (talk | contribs) (Created page with "==settings.gradle== pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() maven { url "https:/...") |
Onnowpurbo (talk | contribs) |
||
(5 intermediate revisions by the same user not shown) | |||
Line 35: | Line 35: | ||
} | } | ||
+ | ==activity_main.xml== | ||
− | |||
<?xml version="1.0" encoding="utf-8"?> | <?xml version="1.0" encoding="utf-8"?> | ||
Line 47: | Line 47: | ||
<Button | <Button | ||
− | android:id="@+id/ | + | android:id="@+id/btnConnect" |
android:layout_width="match_parent" | android:layout_width="match_parent" | ||
− | android:layout_height=" | + | android:layout_height="70dp" |
+ | android:layout_marginBottom="10dp" | ||
android:text="Connect" | android:text="Connect" | ||
− | app:layout_constraintBottom_toTopOf="@+id/ | + | app:layout_constraintBottom_toTopOf="@+id/btnPublish" |
− | + | tools:layout_editor_absoluteX="0dp" /> | |
− | |||
− | tools:layout_editor_absoluteX=" | ||
<Button | <Button | ||
− | android:id="@+id/ | + | android:id="@+id/btnPublish" |
android:layout_width="match_parent" | android:layout_width="match_parent" | ||
− | android:layout_height=" | + | android:layout_height="70dp" |
− | android:layout_marginBottom=" | + | android:layout_marginBottom="10dp" |
android:text="Publish" | android:text="Publish" | ||
− | app:layout_constraintBottom_toTopOf="@+id/ | + | app:layout_constraintBottom_toTopOf="@+id/btnSubscribe" |
− | tools:layout_editor_absoluteX="0dp" /> | + | tools:layout_editor_absoluteX="0dp" /> |
<Button | <Button | ||
− | android:id="@+id/ | + | android:id="@+id/btnSubscribe" |
android:layout_width="match_parent" | android:layout_width="match_parent" | ||
− | android:layout_height=" | + | android:layout_height="70dp" |
− | android:layout_marginBottom=" | + | android:layout_marginBottom="10dp" |
android:text="Subscribe" | android:text="Subscribe" | ||
− | app:layout_constraintBottom_toTopOf="@+id/ | + | 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" /> | tools:layout_editor_absoluteX="0dp" /> | ||
− | + | ||
<Button | <Button | ||
− | android:id="@+id/ | + | android:id="@+id/btndisConnect" |
android:layout_width="match_parent" | android:layout_width="match_parent" | ||
− | android:layout_height=" | + | android:layout_height="70dp" |
− | android:layout_marginBottom=" | + | android:layout_marginBottom="52dp" |
android:text="Disconnect" | android:text="Disconnect" | ||
app:layout_constraintBottom_toBottomOf="parent" | app:layout_constraintBottom_toBottomOf="parent" | ||
Line 84: | Line 91: | ||
</androidx.constraintlayout.widget.ConstraintLayout> | </androidx.constraintlayout.widget.ConstraintLayout> | ||
− | |||
==MainActivity.java== | ==MainActivity.java== | ||
Line 92: | Line 98: | ||
import android.os.Bundle; | import android.os.Bundle; | ||
import android.view.View; | import android.view.View; | ||
− | import android.widget. | + | import android.widget.TextView; |
import androidx.appcompat.app.AppCompatActivity; | import androidx.appcompat.app.AppCompatActivity; | ||
Line 98: | Line 104: | ||
import org.eclipse.paho.client.mqttv3.MqttException; | import org.eclipse.paho.client.mqttv3.MqttException; | ||
import org.eclipse.paho.client.mqttv3.MqttMessage; | import org.eclipse.paho.client.mqttv3.MqttMessage; | ||
− | import org.greenrobot.eventbus. | + | import org.greenrobot.eventbus.EventBus; |
import org.greenrobot.eventbus.Subscribe; | import org.greenrobot.eventbus.Subscribe; | ||
− | |||
public class MainActivity extends AppCompatActivity { | public class MainActivity extends AppCompatActivity { | ||
Line 117: | Line 122: | ||
setContentView(R.layout.activity_main); | setContentView(R.layout.activity_main); | ||
− | findViewById(R.id. | + | 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 | @Override | ||
public void onClick(View v) { | public void onClick(View v) { | ||
Line 125: | Line 133: | ||
boolean b = MqttManager.getInstance().creatConnect(URL, userName, password, clientId); | boolean b = MqttManager.getInstance().creatConnect(URL, userName, password, clientId); | ||
// Logger.d("isConnected: " + b); | // Logger.d("isConnected: " + b); | ||
+ | // EventBus.getDefault().register( this ); | ||
} | } | ||
}).start(); | }).start(); | ||
} | } | ||
− | }); | + | }); |
− | findViewById(R.id. | + | findViewById(R.id.btnPublish).setOnClickListener(new View.OnClickListener() { |
@Override | @Override | ||
public void onClick(View v) { | public void onClick(View v) { | ||
Line 136: | Line 145: | ||
@Override | @Override | ||
public void run() { | public void run() { | ||
− | MqttManager.getInstance().publish("demo", 2, "MQTT Test | + | MqttManager.getInstance().publish("demo", 2, "MQTT Android Test".getBytes()); |
} | } | ||
}).start(); | }).start(); | ||
Line 142: | Line 151: | ||
}); | }); | ||
− | findViewById(R.id. | + | findViewById(R.id.btnSubscribe).setOnClickListener(new View.OnClickListener() { |
@Override | @Override | ||
public void onClick(View v) { | public void onClick(View v) { | ||
Line 149: | Line 158: | ||
public void run() { | public void run() { | ||
MqttManager.getInstance().subscribe("demo", 2); | MqttManager.getInstance().subscribe("demo", 2); | ||
+ | // EventBus.getDefault().register( this ); | ||
} | } | ||
}).start(); | }).start(); | ||
} | } | ||
}); | }); | ||
− | + | ||
− | findViewById(R.id. | + | findViewById(R.id.btndisConnect).setOnClickListener(new View.OnClickListener() { |
@Override | @Override | ||
public void onClick(View v) { | public void onClick(View v) { | ||
Line 162: | Line 172: | ||
try { | try { | ||
MqttManager.getInstance().disConnect(); | MqttManager.getInstance().disConnect(); | ||
− | } catch (MqttException e) { | + | // EventBus.getDefault().unregister( this ); |
− | + | } catch (MqttException e) { | |
+ | |||
} | } | ||
} | } | ||
Line 169: | Line 180: | ||
} | } | ||
− | }); | + | }); |
− | + | ||
+ | EventBus.getDefault().register(this); | ||
} | } | ||
− | + | ||
/** | /** | ||
* Subscribe to received messages | * Subscribe to received messages | ||
Line 183: | Line 195: | ||
public void onEvent(MqttMessage message) { | public void onEvent(MqttMessage message) { | ||
// Logger.d(message.toString()); | // Logger.d(message.toString()); | ||
− | Toast.makeText(this, message.toString() ,Toast.LENGTH_SHORT).show(); | + | // 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 | ||
} | } | ||
Line 189: | Line 204: | ||
protected void onResume() { | protected void onResume() { | ||
super.onResume(); | super.onResume(); | ||
− | |||
} | } | ||
Line 195: | Line 209: | ||
protected void onPause() { | protected void onPause() { | ||
super.onPause(); | super.onPause(); | ||
− | |||
} | } | ||
@Override | @Override | ||
protected void onDestroy() { | protected void onDestroy() { | ||
+ | EventBus.getDefault().unregister(this); | ||
super.onDestroy(); | super.onDestroy(); | ||
} | } | ||
Line 205: | Line 219: | ||
} | } | ||
+ | ==MqttManager.java== | ||
− | |||
package itts.onno.mqtttest; | package itts.onno.mqtttest; | ||
Line 216: | Line 230: | ||
import org.eclipse.paho.client.mqttv3.MqttMessage; | import org.eclipse.paho.client.mqttv3.MqttMessage; | ||
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; | import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; | ||
− | |||
− | |||
− | + | class MqttManager { | |
// instance | // instance | ||
private static MqttManager mInstance = null; | private static MqttManager mInstance = null; | ||
− | |||
− | |||
// Private instance variables | // Private instance variables | ||
Line 232: | Line 242: | ||
private boolean clean = true; | private boolean clean = true; | ||
+ | // callback | ||
+ | private MqttCallback mCallback; | ||
private MqttManager() { | private MqttManager() { | ||
mCallback = new MqttCallbackBus(); | mCallback = new MqttCallbackBus(); | ||
− | } | + | } |
public static MqttManager getInstance() { | public static MqttManager getInstance() { | ||
Line 241: | Line 253: | ||
} | } | ||
return mInstance; | return mInstance; | ||
− | } | + | } |
/** | /** | ||
Line 253: | Line 265: | ||
} | } | ||
} catch (Exception e) { | } catch (Exception e) { | ||
− | |||
} | } | ||
} | } | ||
Line 290: | Line 301: | ||
client.setCallback(mCallback); | client.setCallback(mCallback); | ||
flag = doConnect(); | flag = doConnect(); | ||
+ | |||
} catch (MqttException e) { | } catch (MqttException e) { | ||
Logger.e(e.getMessage()); | Logger.e(e.getMessage()); | ||
} | } | ||
− | |||
return flag; | return flag; | ||
} | } | ||
/** | /** | ||
− | * | + | * establish connection |
* | * | ||
* @return | * @return | ||
− | + | */ | |
public boolean doConnect() { | public boolean doConnect() { | ||
boolean flag = false; | boolean flag = false; | ||
Line 342: | Line 353: | ||
flag = true; | flag = true; | ||
} catch (MqttException e) { | } catch (MqttException e) { | ||
− | |||
} | } | ||
− | |||
} | } | ||
− | |||
return flag; | return flag; | ||
} | } | ||
Line 370: | Line 378: | ||
// be downgraded to 1 when delivering to the client but messages published at 1 and 0 | // 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. | // will be received at the same level they were published at. | ||
+ | |||
// Logger.d("Subscribing to topic \"" + topicName + "\" qos " + qos); | // Logger.d("Subscribing to topic \"" + topicName + "\" qos " + qos); | ||
try { | try { | ||
client.subscribe(topicName, qos); | client.subscribe(topicName, qos); | ||
flag = true; | flag = true; | ||
+ | |||
} catch (MqttException e) { | } catch (MqttException e) { | ||
− | |||
} | } | ||
} | } | ||
− | |||
return flag; | return flag; | ||
− | |||
} | } | ||
/** | /** | ||
− | * | + | * disconnect the connection |
* | * | ||
* @throws MqttException | * @throws MqttException | ||
Line 393: | Line 400: | ||
} | } | ||
} | } | ||
+ | } | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | ==MqttCallbackBus.java== | ||
+ | |||
+ | |||
+ | |||
+ | package itts.onno.mqtttest; | ||
+ | import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; | ||
+ | import org.eclipse.paho.client.mqttv3.MqttCallback; | ||
+ | import org.eclipse.paho.client.mqttv3.MqttMessage; | ||
+ | import org.greenrobot.eventbus.EventBus; | ||
+ | /** | ||
+ | * Dispatching events using EventBus | ||
+ | * | ||
+ | * @author LichFaker on 16/3/25. | ||
+ | * @Email lichfaker@gmail.com | ||
+ | */ | ||
+ | public class MqttCallbackBus implements MqttCallback { | ||
+ | @Override | ||
+ | public void connectionLost(Throwable cause) { | ||
+ | // Logger.e(cause.getMessage()); | ||
+ | } | ||
+ | @Override | ||
+ | public void messageArrived(String topic, MqttMessage message) { | ||
+ | // Logger.d(topic + "====" + message.toString()); | ||
+ | EventBus.getDefault().post(message); | ||
+ | // Toast.makeText(this, message.toString() ,Toast.LENGTH_SHORT).show(); | ||
+ | } | ||
+ | @Override | ||
+ | public void deliveryComplete(IMqttDeliveryToken token) { | ||
+ | } | ||
} | } | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | ==Pranala Menarik== | ||
+ | |||
+ | * https://github.com/LichFaker/MqttClientAndroid |
Latest revision as of 07:01, 13 April 2022
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(); } } }
MqttCallbackBus.java
package itts.onno.mqtttest; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.greenrobot.eventbus.EventBus; /** * Dispatching events using EventBus * * @author LichFaker on 16/3/25. * @Email lichfaker@gmail.com */ public class MqttCallbackBus implements MqttCallback { @Override public void connectionLost(Throwable cause) { // Logger.e(cause.getMessage()); } @Override public void messageArrived(String topic, MqttMessage message) { // Logger.d(topic + "====" + message.toString()); EventBus.getDefault().post(message); // Toast.makeText(this, message.toString() ,Toast.LENGTH_SHORT).show(); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }