Paho MqttAndroidClient.connect总是失败

前端之家收集整理的这篇文章主要介绍了Paho MqttAndroidClient.connect总是失败前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将消息从 android服务发布到本地服务器.这是我的代码的一部分,最简单的形式基于 here的片段.
MemoryPersistence memPer;
MqttAndroidClient client;

@Override
public IBinder onBind(Intent intent) {
    memPer = new MemoryPersistence();
    client = new MqttAndroidClient(this,"tcp://192.168.1.42:1883","clientid",memPer);

    try {
        client.connect(null,new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken mqttToken) {
                Log.i("MQTT","Client connected");
                Log.i("MQTT","Topics=" + mqttToken.getTopics());

                MqttMessage message = new MqttMessage("Hello,I am Android Mqtt Client.".getBytes());
                message.setQos(2);
                message.setRetained(false);

                try {
                    client.publish("messages",message);

                    Log.i("MQTT","Message published");

                    client.disconnect();
                    Log.i("MQTT","client disconnected");
                } catch (MqttPersistenceException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(IMqttToken arg0,Throwable arg1) {
                // TODO Auto-generated method stub
                Log.i("MQTT","Client connection Failed: " + arg1.getMessage());
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }

    return mBinder;
}

但总是调用onFailure函数,我得到错误

I/MQTT﹕ Client connection Failed: cannot start service org.eclipse.paho.android.service.MqttService

显然由库返回,因为’listener!= null’,Line 410.使用调试器,它显示’listener = SensorLoggerService $1 @ 3634′. SensorLoggerService是我的服务.

什么可能出错?非常感谢.

解决方法

对我来说同样的问题,在我的情况下问题是< service>标签位于< application>之外标签.

一开始我有这个:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >
...
<service android:name="org.eclipse.paho.android.service.MqttService">
    </service>
...
<application
    android:name="com.mycompany.myapp" ... >
...
</application>

然后我改为:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >
...
<application
    android:name="com.mycompany.myapp" ... >
...
    <service android:name="org.eclipse.paho.android.service.MqttService">
    </service>

</application>

一切正常!

您还需要添加INTERNET和ACCESS_NETWORK_STATE权限,否则您将无法连接.

HTH

猜你在找的Android相关文章