Mqtt客户端
首先我们得需要mqtt3.jar包
mqtt3下载连接
package com.clientmqtt;
import android.content.Context;
import android.telephony.TelephonyManager;
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.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.concurrent.ScheduledExecutorService;
import static android.content.Context.TELEPHONY_SERVICE;
public class ClientMQTT {
//注意这里 改成搭建服务器地址
public static final String HOST = "tcp://192.168.10.67:61613";
public static final String TOPIC = "topic11";
private String clientid = "client";
private MqttClient client;
private MqttConnectOptions options;
private String userName = "admin";
private String passWord = "password";
private MqttCallback mMqttCallback;
private ScheduledExecutorService scheduler;
public void start() {
try {
// host为主机名,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(mMqttCallback);
client.setTimeToWait(500000);
MqttTopic topic = client.getTopic(TOPIC);
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic, "close".getBytes(), 2, true);
client.connect(options);
//订阅消息
int[] Qos = {1};
String[] topic1 = {TOPIC};
client.subscribe(topic1, Qos);
} catch (Exception e) {
e.printStackTrace();
}
}
public ClientMQTT(MqttCallback mqttCallback ,Context context) {
TelephonyManager TelephonyMgr = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
this.clientid=TelephonyMgr.getDeviceId();
this.mMqttCallback=mqttCallback;
start();
}
public void connect() {
try {
client.connect(options);
//订阅消息
int[] Qos = {1};
String[] topic1 = {TOPIC};
client.subscribe(topic1, Qos);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
package com.clientmqtt;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ClientMQTT mClientMQTT;
private TextView mButton;
public Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
mButton.setText(msg.obj+"");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (TextView) findViewById(R.id.jieshou);
findViewById(R.id.create).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mClientMQTT = new ClientMQTT(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
System.out.println("连接断开,可以做重连");
// mClientMQTT.connect();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// subscribe后得到的消息会执行到这里面
System.out.println("接收消息主题 : " + topic);
System.out.println("接收消息Qos : " + message.getQos());
System.out.println("接收消息内容 : " + new String(message.getPayload()));
if("close".equals(new String(message.getPayload()))){
System.out.println("接收消息内容 : " + new String(message.getPayload()));
}else {
Message message1 =new Message();
message1.obj=new String(message.getPayload());
myHandler.sendMessage(message1);
System.out.println("接收消息内容 mButton: " + new String(message.getPayload()));
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
},MainActivity.this);
}
});
findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mClientMQTT.connect();
}
});
findViewById(R.id.disconnect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mClientMQTT.disconnect();
}
});
}
}
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
android:id="@+id/create"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="创建连接!"
/>
android:id="@+id/connect"
android:text="重新连接!"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="50dp"/>
android:id="@+id/disconnect"
android:text="断开连接!"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="50dp"/>
android:id="@+id/jieshou"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
服务端发来的消息
Paste_Image.png