1.添加mqtt包到gradle.build
a.在project的gradle.build中添加地址(P:我下载的参考例子是不用添加的,但是我自己写的时候不添加就编译不过去)
allprojects {
repositories {
google()
jcenter()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
}
b.在app的gradle.build中添加MQTT的依赖
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}
2.在AndroidMenifest.xml中添加权限和service
(P:那个WAKE_LOCK,ACCESS_NETWORK_STATE权限和service一定要添加,之前参考网上的例子写的时候没有注意到要添加service,启动mqtt.connect一直返回连接失败,打印失败信息报cannot start service org.eclipse.paho.android.service.MqttService,然后添加了service又报WAKE_LOCK,ACCESS_NETWORK_STATE权限安全错误,所以一定要注意添加它们)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chenss.baselib">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<categor
Android MQTT连接服务器实践

本文介绍了在Android中实现MQTT连接服务器的步骤,包括在gradle.build中添加依赖,AndroidManifest.xml中设置权限和服务,以及MainActivity的代码实现。强调了添加WAKE_LOCK和ACCESS_NETWORK_STATE权限及MqttService的重要性,因为缺少这些会导致连接失败。
最低0.47元/天 解锁文章
1640

被折叠的 条评论
为什么被折叠?



