我刚刚开始使用Java Android编程,甚至是Java编程,我想使用某个MqttHandler类实现Paho MQTT Android服务,我想将回调设置为MqttHandler类的参数。关于回调的其他答案一般建议使用接口类,但我不知道它是如何工作的。这就是我的尝试:
public interface InterfaceMqttCallback extends MqttCallbackExtended{
@Override
public void connectComplete(boolean b, String s);
@Override
public void connectionLost(Throwable throwable);
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception ;
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken);
}
MqttHandler类构造函数:
public MqttHandler(Context context, InterfaceMqttCallback mqttCallbackExtended){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(mqttCallbackExtended);
connect();
}
初始化MqttHandler的Activity中的函数:
private void startMqtt(){
mqttHandler = new MqttHandler(getApplicationContext(), new InterfaceMqttCallback() {
@Override
public void connectComplete(boolean b, String s) {
Log.w("Anjing", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
但是当我测试它时,我认为没有设置回调,因为没有收到任何消息。那么我尝试直接在MqttHandler中设置回调,它可以工作,收到消息。
public MqttHandler(Context context, InterfaceMqttCallback mqttCallbackExtended){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new InterfaceMqttCallback() {
@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
那么问题是什么?提前谢谢..
编辑:我当然可以将MqttHandler类中的mqttAndroidClient
变量设置为public,但它是否安全?
答案 0 :(得分:1)
设置回调处理程序的正确方法是在MQTT客户端中设置它,如下所示:
public class MTTConnector {
public void connect {
MqttAndroidClient mqttClient = new MqttAndroidClient(BaseApplication.getAppContext(), broker, MQTT_CLIENT_ID);
mqttClient.setCallback(new MqttCallbackHandler(BaseApplication.getAppContext()));
}
}
public class MqttCallbackHandler implements MqttCallbackExtended {
@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
}
如果您使用的是最新版本,则回调需要实现MqttCallbackExtended类,有关在线GitHub项目的更多详细信息,请参阅以下链接。
在您的活动中初始化MTTConnector并呼叫连接。
希望得到这个帮助。
干杯!