Android中MQTT的简单实现(只是连接到服务器,未实现发送、接受信息)

本文介绍了在Android中实现MQTT连接服务器的步骤,包括在gradle.build中添加依赖,AndroidManifest.xml中设置权限和服务,以及MainActivity的代码实现。强调了添加WAKE_LOCK和ACCESS_NETWORK_STATE权限及MqttService的重要性,因为缺少这些会导致连接失败。
摘要由CSDN通过智能技术生成

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" />
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值