android mqtt 权限,MQTT在Android中的使用

MQTT简介

MQTT 是一种基于发布订阅模型的即时通讯协议,主要应用于物联网设备中

配置

添加依赖

在project的gradle中添加远程maven仓库

repositories {

maven {

url "https://repo.eclipse.org/content/repositories/paho-snapshots/"

}

}

在app的gradle中添加两个mqtt库

dependencies {

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'

implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

}

添加必要的权限

封装

MQTT主要需要MQ服务器地址、用户名、密码、发布主题和响应主题,以及客户端唯一标识

需要注意的是服务器地址如果是IP地址的话,格式是tcp://192.168.168.101:1883,由tcp协议+ip地址+端口号

组成。若为域名的方式则只需要tcp协议+域名,端口号可忽略,默认端口是1883。

使用方法:

1.注册Service。

为了防止内存泄漏,我们使用Application的Context

2.MyMqttService.startService(BaseApplication.getContext()); //开启服务

public class MyMqttService extends Service {

public final static String TAG = MyMqttService.class.getSimpleName();

public static MqttAndroidClient mqttAndroidClient;

private static MqttConnectOptions mMqttConnectOptions;

public static String HOST = Config.getMqHost();//服务器地址(协议+地址+端口号)

public String USERNAME = Config.getMqUserName();//用户名

public String PASSWORD = Config.getMqPassWord();//密码

public static String PUBLISH_TOPIC = Config.getMqResponseTopic();//发布主题

public static String RESPONSE_TOPIC = Config.getMqResponseTopic();//响应主题

public String CLIENTID = DeviceUtils.getIMEI();//设备唯一标识

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

init();

return START_NOT_STICKY;//非粘性的 service强制杀死后,不会尝试重新启动service

}

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

}

/**

* 开启服务

*/

public static void startService(Context mContext) {

mContext.startService(new Intent(mContext, MyMqttService.class));

}

/**

* 发布 (模拟其他客户端发布消息)

*

* @param message 消息

*/

public static void publish(String message) {

String topic = PUBLISH_TOPIC;

Integer qos = 1;

Boolean retained = false;

try {

//参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息

mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue());

} catch (MqttException e) {

e.printStackTrace();

}

}

/**

* 响应 (收到其他客户端的消息后,响应给对方告知消息已到达或者消息有问题等)

*

* @param message 消息

*/

public static void response(String message) {

String topic = RESPONSE_TOPIC;

Integer qos = 1;

Boolean retained = false;

try {

//参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息

mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue());

} catch (MqttException e) {

e.printStackTrace();

}

}

/**

* 初始化

*/

private void init() {

String serverURI = HOST; //服务器地址(协议+地址+端口号)

LogUtils.i(TAG, "初始化MQ" + serverURI);

if (mqttAndroidClient == null) {

mqttAndroidClient = new MqttAndroidClient(this, serverURI, CLIENTID);

mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调

}

if (mMqttConnectOptions == null) {

mMqttConnectOptions = new MqttConnectOptions();

mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存

mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间,单位:秒

mMqttConnectOptions.setKeepAliveInterval(20); //设置心跳包发送间隔,单位:秒

mMqttConnectOptions.setUserName(USERNAME); //设置用户名

mMqttConnectOptions.setPassword(PASSWORD.toCharArray()); //设置密码

}

// last will message

boolean doConnect = true;

String message = "{\"terminal_uid\":\"" + CLIENTID + "\"}";

String topic = PUBLISH_TOPIC;

Integer qos = 1;

Boolean retained = true;

if ((!message.equals("")) || (!topic.equals(""))) {

// 最后的遗嘱

try {

mMqttConnectOptions.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());

} catch (Exception e) {

LogUtils.i(TAG, "Exception Occured");

doConnect = false;

iMqttActionListener.onFailure(null, e);

}

}

if (doConnect) {

doClientConnection();

}

}

/**

* 连接MQTT服务器

*/

private static void doClientConnection() {

try {

if (!mqttAndroidClient.isConnected() && isConnectIsNomarl()) {

LogUtils.i(TAG, "连接MQTT服务器" + HOST);

mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 判断网络是否连接

*/

private static boolean isConnectIsNomarl() {

ConnectivityManager connectivityManager = (ConnectivityManager) BaseApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo info = connectivityManager.getActiveNetworkInfo();

if (info != null && info.isAvailable()) {

String name = info.getTypeName();

LogUtils.i(TAG, "当前网络名称:" + name);

return true;

} else {

LogUtils.i(TAG, "没有可用网络");

/*没有可用网络的时候,延迟3秒再尝试重连*/

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

LogUtils.i(TAG, "没有可用网络doClientConnection");

doClientConnection();

}

}, 3000);

return false;

}

}

//MQTT是否连接成功的监听

private static IMqttActionListener iMqttActionListener = new IMqttActionListener() {

@Override

public void onSuccess(IMqttToken arg0) {

LogUtils.i(TAG, "连接成功 " + HOST);

try {

if (mqttAndroidClient != null) {

mqttAndroidClient.subscribe(PUBLISH_TOPIC, 1);//订阅主题,参数:主题、服务质量

}

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

public void onFailure(IMqttToken arg0, Throwable arg1) {

arg1.printStackTrace();

LogUtils.i(TAG, "连接失败 ");

doClientConnection();//连接失败,重连(可关闭服务器进行模拟)

}

};

//订阅主题的回调

private MqttCallback mqttCallback = new MqttCallback() {

@Override

public void messageArrived(String topic, MqttMessage msgStr) throws Exception {

try {

String enCodeMsg = new String(msgStr.getPayload());

LogUtils.i(TAG, "收到消息: " + enCodeMsg);

//收到消息,这里弹出Toast表示。如果需要更新UI,可以使用广播或者EventBus进行发送

//收到其他客户端的消息后,响应给对方告知消息已到达或者消息有问题等

response("message arrived");

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

public void deliveryComplete(IMqttDeliveryToken arg0) {

}

@Override

public void connectionLost(Throwable arg0) {

LogUtils.i(TAG, "连接断开 ");

doClientConnection();//连接断开,重连

}

};

public static void disconnect(Context context) {

try {

if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {

mqttAndroidClient.unsubscribe(PUBLISH_TOPIC);

mqttAndroidClient.unregisterResources();

mqttAndroidClient.disconnect(0); //断开连接

mqttAndroidClient = null;

context.stopService(new Intent(context, MyMqttService.class));

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,如果您想在 IntentService 使用 MQTT 协议进行消息传输,可以使用 Eclipse Paho Android 客户端库。以下是在 IntentService 使用 Paho Android 客户端库实现 MQTT 的基本步骤: 1. 添加 Paho Android 客户端库到您的项目。 2. 在 IntentService 的 `onCreate()` 方法创建 MQTT 客户端并连接到 MQTT 代理服务器。您需要指定代理服务器的地址和端口号。可以使用 `MqttConnectOptions` 类设置连接选项,例如设置连接的用户名和密码、清除会话标志等。 3. 在 `onHandleIntent()` 方法订阅主题、发布消息和处理接收到的消息。您需要实现 `MqttCallback` 接口,并在回调方法处理接收到的消息。 以下是在 IntentService 连接到 MQTT 代理服务器的示例代码: ```java public class MyIntentService extends IntentService { private static final String TAG = MyIntentService.class.getSimpleName(); private MqttAndroidClient client; public MyIntentService() { super(TAG); } @Override public void onCreate() { super.onCreate(); String brokerUrl = "tcp://mqtt.eclipse.org:1883"; String clientId = MqttClient.generateClientId(); client = new MqttAndroidClient(this, brokerUrl, clientId); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("username"); options.setPassword("password".toCharArray()); options.setCleanSession(true); try { IMqttToken token = client.connect(options); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to connect to MQTT broker", e); } } @Override protected void onHandleIntent(Intent intent) { // 在这里订阅主题、发布消息和处理接收到的消息 // ... // 订阅主题 String topic = "my/topic"; int qos = 1; try { IMqttToken token = client.subscribe(topic, qos); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to subscribe to topic: " + topic, e); } // 发布消息 String message = "Hello, MQTT!"; try { client.publish(topic, message.getBytes(), qos, false); } catch (MqttException e) { Log.e(TAG, "Failed to publish message: " + message, e); } } @Override public void onDestroy() { super.onDestroy(); try { IMqttToken token = client.disconnect(); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to disconnect from MQTT broker", e); } } } ``` 您还需要实现 `MqttCallback` 接口并在回调方法处理接收到的消息。例如: ```java client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { // 处理连接丢失事件 } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // 处理接收到的消息 String payload = new String(message.getPayload()); Log.d(TAG, "Received message: " + payload); } @Override public void deliveryComplete(IMqttDeliveryToken token) { // 处理消息发送完成事件 } }); ``` 在 `onDestroy()` 方法断开 MQTT 客户端与代理服务器的连接。 希望这些信息能对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值