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,clIEntID); mqttAndroIDClIEnt.setCallback(new InterfaceMqttCallback() { @OverrIDe public voID connectComplete(boolean b,String s) { Log.w("mqtt",mqttMessage.toString()); } @OverrIDe public voID deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }); connect();}
所以有什么问题?提前致谢..
编辑:当然我可以将MqttHandler类中的mqttAndroIDClIEnt变量设置为public,但它是否安全?
解决方法 设置回调处理程序的正确方法是在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,mqttMessage.toString()); } @OverrIDe public voID deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }
如果您使用的是最新版本,则回调需要实现MqttCallbackExtended类,有关在线GitHub项目的更多详细信息,请参阅以下链接.
MqttCallbackExtended.java
在您的活动内部初始化MTTConnector并调用connect.
希望这个帮助.
干杯!
总结以上是内存溢出为你收集整理的Paho-mqtt在不同类的android java中回调全部内容,希望文章能够帮你解决Paho-mqtt在不同类的android java中回调所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)