一、MQTT的创建和connect流程
1.Android端实现mqtt,首先会new一个MqttAndroidClient,并传入需要的参数。
首先,MqttAndroidClient是如何创建的呢?
public MqttAndroidClient(Context context, String serverURI,
String clientId, MqttClientPersistence persistence, Ack ackType) {
myContext = context;
this.serverURI = serverURI;
this.clientId = clientId;
this.persistence = persistence;
messageAck = ackType;
}
MqttAndroidClient本身是继承Broadcast的子类,他的构造器需要传入上面的参数,必须传入的为
public MqttAndroidClient(Context context, String serverURI,
String clientId) {
this(context, serverURI, clientId, null, Ack.AUTO_ACK);
}
2.connect的核心方法:
@Override
public IMqttToken connect(MqttConnectOptions options, Object userContext,
IMqttActionListener callback) throws MqttException {
IMqttToken token = new MqttTokenAndroid(this, userContext,
callback);
connectOptions = options;
connectToken = token;
/*
* The actual connection depends on the service, which we start and bind
* to here, but which we can't actually use until the serviceConnection
* onServiceConnected() method has run (asynchronously), so the
* connection itself takes place in the onServiceConnected() method
*/
if (mqttService == null) { // First time - must bind to the service
Intent serviceStartIntent = new Intent();
serviceStartIntent.setClassName(myContext, SERVICE_NAME);
Object service = myContext.startService(serviceStartIntent);
if (service == null) {
IMqttActionListener listener = token.getActionCallback();
if (listener != null) {
listener.onFailure(token, new RuntimeException(
"cannot start service " + SERVICE_NAME));
}
}
// We bind with BIND_SERVICE_FLAG (0), leaving us the manage the lifecycle
// until the last time it is stopped by a call to stopService()
myContext.bindService(serviceStartIntent, serviceConnection,
Context.BIND_AUTO_CREATE);
if (!receiverRegistered) registerReceiver(this);
}
else {
pool.execute(new Runnable() {
@Override
public void run() {
doConnect();
//Register receiver to show shoulder tap.
if (!receiverRegistered) registerReceiver(MqttAndroidClient.this);
}
});
}
return token;
}
返回一个IMqttToken对象,这里首先new一个MqttTokenAndroid对象,然后去判断是否存在MqttService实例。
没有的话会创建一个,如果创建失败直接调用IMqttActionListener的onFailure回调。
成功的话绑定一个bindService,传入ServiceConnection参数对象。
而ServiceConnection的成功回调中有个doConnect()方法,里面会调用MqttService的connect方法从而建立Mqtt的连接。
而在MqttService的connect方法里面,会创建一个MqttConnection对象,调用他的connect方法。
而MqttConnection的connect方法里面会判断是否有MqttAsyncClient实例,如果没有会创建他的实例并调用他的connect方法
// if myClient is null, then create a new connection
else {
alarmPingSender = new AlarmPingSender(service);
myClient = new MqttAsyncClien