1,导入2个jar包
2,在AndroidManifest中添加Service
<service android:name="org.eclipse.paho.android.service.MqttService" />
然后在代码中定义自己的Servce.例如我的叫:MQTTService
3,在我们服务启动的时候调用init方法进行初始化MQTT各种操作
private void init() {
String uri = host;
client = new MqttAndroidClient(getApplicationContext(), uri, clientId);
// 设置MQTT监听并且接受消息
client.setCallback(mqttCallback);
conOpt = new MqttConnectOptions();
// 清除缓存
conOpt.setCleanSession(true);
// 设置超时时间,单位:秒
conOpt.setConnectionTimeout(20);
// 心跳包发送间隔,单位:秒
conOpt.setKeepAliveInterval(3 * 60);
// 用户名
conOpt.setUserName(userName);
// 密码
conOpt.setPassword(passWord.toCharArray()); //将字符串转换为字符串数组
//断开后,是否自动连接
conOpt.setAutomaticReconnect(true);
// last will message
boolean doConnect = true;
String message = "{\"clientId\":\"" + clientId + "\"}";
Log.e(getClass().getName(), "message is:" + message);
String topic = "track";
Integer qos = 1;
Boolean retained = false;
if ((!message.equals("")) || (!topic.equals(""))) {
// 最后的遗嘱
// MQTT本身就是为信号不稳定的网络设计的,所以难免一些客户端会无故的和Broker断开连接。
//当客户端连接到Broker时,可以指定LWT,Broker会定期检测客户端是否有异常。
//当客户端异常掉线时,Broker就往连接时指定的topic里推送当时指定的LWT消息。
try {
conOpt.setWill("public", message.getBytes(), 1, retained.booleanValue());
// conOpt.setWill("e-wallet", message.getBytes(), 2, retained.booleanValue());
} catch (Exception e) {
Log.e(TAG, "Exception Occured", e);
doConnect = false;
iMqttActionListener.onFailure(null, e);
}
}
if (doConnect) {
doClientConnection();
}
}
其中userName passWord和host是与后台商量一致的
前面的工作往后才能后,我们就去调用doClientConnection连接mqtt服务,为了防止重复连接我们添加一个标志位doConnect
/**
* 连接MQTT服务器
*/
private void doClientConnection() {
if (!client.isConnected()) {
try {
client.connect(conOpt, null, iMqttActionListener);