Android Studio - MQTT 未连接 [英] Android Studio - MQTT not connecting

查看:73
本文介绍了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 以包括:

  • (从 application 标签内部)

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

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

  • 编译'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'

编译'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天全站免登陆