參考資料:http://blog.csdn.net/qq_17250009/article/details/52774472
MQTT官網:http://mqtt.org/
MQTT介紹:http://www.ibm.com
MQTT Android github:https://github.com/eclipse/paho.mqtt.android
MQTT API:http://www.eclipse.org/paho/files/javadoc/index.html
MQTT Android API: http://www.eclipse.org/paho/files/android-javadoc/index.html
1下載mqtt包,導入工程
新建一個空安卓工程

首先我們需要找到MQTT通信的java包,導入Android Studio
下載鏈接:https://pan.baidu.com/s/1nw39tYp
將包放在工程app/libs下面,然后右擊 以包的形式導入。

切換工程菜單視圖

右擊加進來的mqtt包,選擇 “as librriary import”

彈出來一個文本框,只有一個 “app”選擇,直接點擊"ok"。
2 工程代碼
2.1 開啟權限
切換工程菜單視圖


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
2.2 布局文件
添加兩個按鈕

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="connect"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"/>
</LinearLayout>
2.3 主代碼

package com.espressif.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
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.MemoryPersistence;
import java.util.concurrent.ScheduledExecutorService;
public class MainActivity extends AppCompatActivity {
public String TAG="MyTAG";
//private String host = "tcp://內網ip:服務器端口號";
private String host = "tcp://www.dongvdong.top:1883"; // ip:端口號www.dongvdong.top:1883http://www.dongvdong.top:1883/
private String userName = "dongdong";
private String passWord = "dongdong";
private String clientId="AndroidClient1";
private int i = 1;
private MqttClient client;
private String myTopic = "test/key1";
private MqttConnectOptions options;
private ScheduledExecutorService scheduler;
public Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
try {
client.subscribe(myTopic, 1);
} catch (Exception e) {
e.printStackTrace();
}
}else if(msg.what==2){
Toast.makeText(MainActivity.this,"fail",Toast.LENGTH_SHORT).show();
}else if(msg.what==3){
Toast.makeText(MainActivity.this,(String)msg.obj,Toast.LENGTH_SHORT).show();
Log.d(TAG, "handleMessage");
}
}
};
Button button1=(Button)findViewById(R.id.button1);
Button button2=(Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
class MyThread extends Thread{
@Override
public void run(){
init();
try {
client.connect(options);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);//連接成功
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = 2;
handler.sendMessage(msg);
//連接失敗
}
}
}
new MyThread().start();
}
});
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
publish("on");
}
});
}
private void init() {
try {
//host為主機名,test為clientid即連接MQTT的客戶端ID,一般以客戶端唯一標識符表示,MemoryPersistence設置clientid的保存形式,默認為以內存保存
client = new MqttClient(host, clientId,
new MemoryPersistence());
//MQTT的連接設置
options = new MqttConnectOptions();
//設置是否清空session,這里如果設置為false表示服務器會保留客戶端的連接記錄,這里設置為true表示每次連接到服務器都以新的身份連接
options.setCleanSession(true);
//設置連接的用戶名
options.setUserName(userName);
//設置連接的密碼
options.setPassword(passWord.toCharArray());
// 設置超時時間 單位為秒
options.setConnectionTimeout(10);
// 設置會話心跳時間 單位為秒 服務器會每隔1.5*20秒的時間向客戶端發送個消息判斷客戶端是否在線,但這個方法並沒有重連的機制
options.setKeepAliveInterval(20);
//設置回調
client.setCallback(mqttCallback);
} catch (Exception e) {
e.printStackTrace();
}
}
private MqttCallback mqttCallback = new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {//This method is called when a message arrives from the server
String str1 = new String(message.getPayload());
Log.d(TAG, "messageArrived: "+str1);
Message msg=new Message();
msg.what=3;
msg.obj=str1;
handler.sendMessage(msg);
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
//Called when delivery for a message has been completed
}
@Override
public void connectionLost(Throwable arg0) {
// This method is called when the connection to the server is lost.
Log.d(TAG, "connectionLost: ");
}
};
public void publish(String msg){
String topic = myTopic;
Integer qos = 0;
Boolean retained = false;
try {
client.publish(topic, msg.getBytes(), qos.intValue(), retained.booleanValue());
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
scheduler.shutdown();
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
3 運行結果
自己發送話題,自己訂閱自己

使用一個mqtt調試助手

4 說明
1 這個沒有斷掉重連機制
2 之只是一個最基礎版的mqtt測試通信
3 未來加入 二維碼掃描
動態控件添加
各種圖標控制
