Android消息推送MQTT填坑Android 集成 mqtt 开启关闭⽹络 应⽤崩溃
⼀.开发环境
Android studio kotlin
前提是你需要有⼀个MQTT代理服务器可以连接,这⾥我也写了⼀篇说明的⽂档,以供参考,链接如下:
官⽅demo
注:git clone 后切换到develop版本 ,master版本在最新 Android studio中不能运⾏
以下是我的app版本,⽬的是让你看到我的版本有多⾼,不是让你改成我的⼀样
compileSdkVersion 30
buildToolsVersion "30.0.2"
minSdkVersion 21
targetSdkVersion 30
⼆.集成步骤
1.依赖
//MQTT
peter pan
implementation 'lip.lip.paho.client.mqttv3:1.1.0' implementation 'lip.lip.paho.android.rvice:1.1.1'
//解决Android开发中LocalBroadcastManager类⽆法使⽤的问题
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
2.权限
smoking是什么意思//MQTT
<us-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<us-permission android:name="android.permission.INTERNET"/>
<us-permission android:name="android.permission.WAKE_LOCK"/>
3.服务
<!--MqttService-->
<rvice android:name="lip.paho.android.rvice.MqttService" />
4.将mqtt集成在MyApplication中
使⽤代码写在MyApplication能保证程序⼀直活着,随时能接收订阅的消息,另外程序中设置了断开重连机制
class MyApplication : Application() {
/*全局单例 */
companion object {
private const val TAG = "MyApplication"
//全局上下⽂
lateinit var context: Context
// 单例不会是null 所以使⽤notNull委托
var instance: MyApplication Null()
//MQTT
const val SUBSCRIPTION_TOPIC = "SubscriptionTopic"
const val PUBLISH_TOPIC = "PublishTopic"
const val baURL: String="192.168.1.141"
const val MQTT_SERVER_USERNAME = "admin"
铁路英语
const val MQTT_SERVER_PASSWORD = "admin"
lateinit var mqttAndroidClient: MqttAndroidClient
lateinit var mqttUrl: String
var clientId = "roomAndroidClient"
}
override fun onCreate() {
instance = this
/*全局上下⽂*/
context = applicationContext
initMQTT()
}
薄葬private fun initMQTT() {
mqttUrl = "tcp://192.168.0.141:1883"
//创建mqtt连接
clientId += System.currentTimeMillis()
mqttAndroidClient = MqttAndroidClient(applicationContext, mqttUrl, clientId)
//设置mqtt连接状态回调
//设置mqtt连接状态回调
mqttAndroidClient.tCallback(object : MqttCallbackExtended {
override fun connectComplete(reconnect: Boolean, rverURI: String) {
if (reconnect) {
Log.d("mqtt", "Reconnected to : $rverURI")
// Becau Clean Session is true, we need to re-subscribe
subscribeToTopic()
} el {
Log.d("mqtt", ("Connected to: $rverURI"))
}
}
override fun connectionLost(cau: Throwable) {
Log.d("mqtt", "The Connection was lost.")
}
@Throws(java.lang.Exception::class)
override fun messageArrived(topic: String, message: MqttMessage) {
英语四六级成绩查询时间Log.d("mqtt", "Incoming message: " + String(message.payload))
方向英文
}
override fun deliveryComplete(token: IMqttDeliveryToken) {}
} )
//设置mqtt连接选项(⾃动重连)
val mqttConnectOptions = MqttConnectOptions()
mqttConnectOptions.isAutomaticReconnect = true
mqttConnectOptions.isCleanSession = fal
mqttConnectOptions.urName = MQTT_SERVER_USERNAME
绝命毒师大结局mqttConnectOptions.password = MQTT_CharArray()
//连接mqtt
Log.d("mqtt", "Connecting to $mqttUrl");
meritoverride fun onSuccess(asyncActionToken: IMqttToken) {
//断开连接的缓冲选项
val disconnectedBufferOptions = DisconnectedBufferOptions()
disconnectedBufferOptions.isBufferEnabled = true
disconnectedBufferOptions.bufferSize = 100
disconnectedBufferOptions.isPersistBuffer = fal
disconnectedBufferOptions.isDeleteOldestMessages = fal
mqttAndroidClient.tBufferOpts(disconnectedBufferOptions)
//订阅主题
subscribeToTopic()
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.d("mqtt", "Failed to connect to: $mqttUrl")
}
})
}
//订阅
fun subscribeToTopic() {
/
/订阅动作回调
mqttAndroidClient.subscribe(SUBSCRIPTION_TOPIC, 0, null, object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken) {
Log.d("mqtt", "Subscribed!")
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.d("mqtt", "Failed to subscribe")
}
})
}
stiefel//发布
fun publishMessage(publishMessage: String) {
recruitment
val message = MqttMessage()
message.payload = ByteArray()
mqttAndroidClient.publish(PUBLISH_TOPIC, message)
Log.d("mqtt", "Message Published")
if (!mqttAndroidClient.isConnected) {
Log.d(
"mqtt",
String() + " messages in buffer." )
}
}
}
5.别忘记将MyApplication添加到清单⽂件中
<application
android:name=".MyApplication"
...>
...
</application>
三.运⾏,报错,解决办法
1.报错情景描述:关闭⽹络,app启动,启动⽹络,崩溃,崩溃信息如下