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" />