当前位置:   article > 正文

android mqtt详解_android中mqtt怎么做

android mqttclientsslconfig

展开全部

MQTT连接建立的代码e68a84e8a2ad62616964757a686964616f31333361326339(SSL方式)

[java] view plain copy

public static void connect(Driver driver) {

ServerConfig serverConfig = UserModule.Instance.getServerConfig();

MqttConnectOptions conOpt = new MqttConnectOptions();

try {

SSLContext sslContext;

KeyStore ts = KeyStore.getInstance("BKS");

ts.load(context.getResources().openRawResource(R.raw.test_cert),

"123456".toCharArray());

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");

tmf.init(ts);

TrustManager[] tm = tmf.getTrustManagers();

sslContext = SSLContext.getInstance("TLS");

sslContext.init(null, tm, null);

SocketFactory factory = sslContext.getSocketFactory();

conOpt.setSocketFactory(factory);

} catch (Exception e) {

e.printStackTrace();

}

[java] view plain copy

//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);

}

}

}

发布(publish)代码

[java] view plain copy

public static void publish(String clientHandle, String topic,

JSONObject jsonObj, int qos) {

MqttClientAndroidService client = Connections.getInstance(context)

.getConnection(clientHandle).getClient();

if (!isConnected(context)) {

try {

client.connect();

} catch (MqttException e) {

e.printStackTrace();

}

Toast.makeText(context, "please try again", Toast.LENGTH_SHORT)

.show();

return;

}

if (topic == null) {

Toast.makeText(context, "can not get other's identity for now",

Toast.LENGTH_SHORT).show();

return;

}

String[] args = new String[2];

if (jsonObj.optLong("time") != 0) {

args[0] = String.valueOf(jsonObj.optLong("time"));

args[1] = topic;

}

Boolean retained = Boolean.parseBoolean(context.getResources()

.getString(R.string.retained));

try {

client.publish(topic, jsonObj.toString().getBytes(), qos, retained,

null, new ActionListener(context, Action.PUBLISH, null,

clientHandle, args));

} catch (MqttSecurityException e) {

Log.e(TAG,

"Failed to publish a messged from the client with the handle "

+ clientHandle, e);

} catch (MqttException e) {

Log.e(TAG,

"Failed to publish a messged from the client with the handle "

+ clientHandle, e);

}

}

订阅(subscribe)代码

[java] view plain copy

public static void subscribe(MqttUtilsCallback mqttUtilsCallback,

String clientHandle, String topic) {

MqttClientAndroidService client = Connections.getInstance(context)

.getConnection(clientHandle).getClient();

if (client == null || (client != null && !client.isConnected())) {

Toast.makeText(context, "please connect to server first",

Toast.LENGTH_SHORT).show();

return;

}

if (TextUtils.isEmpty(topic)) {

topic = "hello";

}

String[] topics = new String[1];

topics[0] = topic;

try {

client.subscribe(topic, 1, null, new ActionListener(context,

ActionListener.Action.SUBSCRIBE, mqttUtilsCallback,

clientHandle, topics));

} catch (MqttSecurityException e) {

Log.e(TAG, "Failed to subscribe to" + topic

+ " the client with the handle " + clientHandle, e);

} catch (MqttException e) {

Log.e(TAG, "Failed to subscribe to" + topic

+ " the client with the handle " + clientHandle, e);

}

本回答由提问者推荐

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/535871
推荐阅读
相关标签
  

闽ICP备14008679号