android mqtt详解_android中mqtt怎么做

展开全部

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

}

本回答由提问者推荐

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值