//paho库得
Iterator> it = Connections
.getInstance(context).getConnections().entrySet().iterator();
while (it.hasNext()) {
MqttClientAndroidService detectClient = it.next().getValue()
.getClient();
try {
detectClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
it.remove();
}
// The basic client information
MqttClientAndroidService client;
client = Connections.getInstance(context).createClient(context,
serverConfig.getUri(), serverConfig.clientId);
Integer qos = Integer.parseInt(context.getResources().getString(
R.string.qos));
Boolean retained = Boolean.parseBoolean(context.getResources()
.getString(R.string.retained));
// connection options
int timeout = Integer.parseInt(context.getResources().getString(
(R.string.timeout)));
int keepalive = Integer.parseInt(context.getResources().getString(
R.string.keepalive));
Connection connection = new Connection(serverConfig.getClientHandle(),
serverConfig.clientId, serverConfig.server,
Integer.parseInt(serverConfig.port), context, client,
serverConfig.ssl);
// connection.registerChangeListener(changeListener);
// connect client
String[] actionArgs = new String[1];
actionArgs[0] = serverConfig.clientId;
connection.changeConnectionStatus(ConnectionStatus.CONNECTING);
boolean cleanSession = false;
conOpt.setCleanSession(cleanSession);
conOpt.setConnectionTimeout(timeout);
conOpt.setKeepAliveInterval(keepalive);
if (!TextUtils.isEmpty(serverConfig.user)) {
conOpt.setUserName(serverConfig.user);
}
if (!TextUtils.isEmpty(serverConfig.pwd)) {
conOpt.setPassword(serverConfig.pwd.toCharArray());
}
// conOpt.setPassword("1111".toCharArray());
final ActionListener callback = new ActionListener(context,
ActionListener.Action.CONNECT, driver.getMqttUtilsCallback(),
serverConfig.getClientHandle(), actionArgs);
boolean doConnect = true;
String message = ActivityConstants.message;
String topic = ActivityConstants.topic;
if ((!TextUtils.isEmpty(message) || !TextUtils.isEmpty(topic))) {
// need to make a message since last will is set
try {
conOpt.setWill(topic, message.getBytes(), qos.intValue(),
retained.booleanValue());
} catch (Exception e) {
e.printStackTrace();
doConnect = false;
callback.onFailure(null, e);
}
}
client.setCallback(new MqttCallbackHandler(context, serverConfig
.getClientHandle(), driver));
connection.addConnectionOptions(conOpt);
Connections.getInstance(context).addConnection(connection);
if (doConnect) {
try {
client.connect(conOpt, null, callback);
} catch (MqttException e) {
Log.e(TAG, "MqttException Occured", e);
}
}
}