我想将消息从 android service
发布到本地服务器。这是基于 here fragment 的最简单形式的部分代码。
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
和 WAKE_LOCK
权限。HTH
关于android - Paho MqttAndroidClient.connect 总是失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32413643/