Android Studio-MQTT无法连接 [英] Android Studio - MQTT not connecting

查看:97
本文介绍了Android Studio-MQTT无法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习在Android Studio中使用MQTT协议.使用 mosquitto 代理,我可以在 pub/sub 窗口之间交换消息.但是,当我通过android studio向经纪人发送消息时,该应用程序构建成功,但经纪人端未显示任何内容&系统显示连接失败".相同的代码在Eclipse Java应用程序上可以正常运行,但在android上却无法运行,尽管已添加了必需的库和依赖项.

I have just started learning using MQTT protocol with Android Studio. Using mosquitto broker, I am able to exchange messages between pub/sub windows. But when I send message to broker through android studio, the app builds successfully but nothing displays on broker's end & system prints Connection Failure. The same code works fine on eclipse java application, but not working on android although required libraries and dependencies have been added.

请帮助,我在此基本步骤中缺少什么,以便我可以继续学习.谢谢!

Please help, what am I missing in this basic step so i can learn forward. Thank you!

app-build.gradle

    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

// have added following dependencies

    provided 'com.google.android.things:androidthings:0.2-devpreview'
    provided 'com.google.android.things:androidthings:0.1-devpreview'
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

}

project-build.gradle

   repositories {
            jcenter()
            maven {
                url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
            }    
}

AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.zoha.mqttandroidiot">

    <!-- Permissions the Application Requires -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        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=".HomeActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <!-- Launch activity automatically on boot -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.IOT_LAUNCHER"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>

        </activity>
<service android:name="org.eclipse.paho.android.service.MqttService"/>

    </application>

</manifest>

家庭活动

  public class HomeActivity extends AppCompatActivity{

    MqttAndroidClient client;
   // private static final MemoryPersistence persistence = new MemoryPersistence();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://localhost:1883", "androidSampleClient");
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection was lost!");

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Delivery Complete!");
            }
        });

        try {
            mqttAndroidClient.connect(null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    System.out.println("Connection Success!");
                    try {
                        System.out.println("Subscribing to /test");
                        mqttAndroidClient.subscribe("/test", 0);
                        System.out.println("Subscribed to /test");
                        System.out.println("Publishing message..");
                        mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
                    } catch (MqttException ex) {

                    }

                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    System.out.println("Connection Failure!");
                }
            });
        } catch (MqttException ex) {

        }


    }
    }

推荐答案

我只想添加评论,但是我的代表太低了,所以我将其发布为答案.

I wanted to just add a comment, but my rep is too low...so i'm posting it as an answer.

您说您已正常运行,但由于IllegalArgumentException而无法连接.我遇到了同样的问题,发现您还需要定义协议. 因此,代替"192.168.0.103:1883"尝试:

You said you got everything working but are unable to connect because of the IllegalArgumentException. I had the same problem and found out that you need to define the protocol also. So instead of "192.168.0.103:1883" try:

String serverURI = "tcp://192.168.0.103:1883"

根据我的阅读,您已经做了其他必要的步骤,但是为了给出完整的答案:

From what i read you already did the other necessary steps, but for the sake of giving a complete answer:

  1. 编辑AndroidManifest.xml以包括:

  • <service android:name="org.eclipse.paho.android.service.MqttService" /> (从application标记内部)

<uses-permission android:name="android.permission.INTERNET" />

编辑build.gradle以包含(在dependencies部分中):

Edit the build.gradle to include (in the dependencies section):

  • compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'

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

使用MqttAndroidClient(而不是MqttClient)

将代码放入"onSuccess"回调中,以避免由于方法异步而引起任何问题(如THEPATEL的回答所示):

Put your code in the "onSuccess" callback, to avoid any problems due to the methods being asynchronous (as shown by THEPATEL's answer):

MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setKeepAliveInterval(60);//seconds
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setAutomaticReconnect(true);

mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            //Treat success here (subscribe, publish etc)
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            //Treat failure here
        }
    });

这篇关于Android Studio-MQTT无法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆