在下面,当我运行它并故意关闭 WiFi 时,回调clientCallBack.connectionLost
会显示Log.d(TAG, "@connectionLost: MQTT Server connection lost");
两次消息。当我重新连接时,回调中的消息Log.i(TAG, "@onSuccess: Connection Successful.");
只client_1.connect
显示一次。
任何人都可以解释为什么我两次收到来自回调的消息?
代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mqtt_proj_01_layout);
sdCard = Environment.getExternalStorageDirectory();
folder = new File(sdCard + directory);
if (!folder.exists())
folder.mkdir();
final MqttClientPersistence persistenceDataDir = new MqttDefaultFilePersistence(folder.toString());
final MqttAndroidClient client_1 = new MqttAndroidClient(getApplicationContext(), serverURI, clientID, persistenceDataDir, Ack.AUTO_ACK);
MqttConnectOptions opts = new MqttConnectOptions();
opts.setCleanSession(false);
opts.setWill(WILL_TOPIC, WILL_MSG.getBytes(), 1, true);
opts.setKeepAliveInterval(keepAliveInterval);
if (client_1 != null) {
//bind the callback to the client object before the client connect o the server so that you get notified regarding any
//pending notifications.this is called Asynchronous massaging
client_1.setCallback(new clientCallBack());
try {
/**
* For synchronous Client " events that happens synchronously, in which the call will lock and return either
* onSuccess or onFailure.
*/
client_1.connect(opts, getApplicationContext(), new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "@onSuccess: Connection Successful.");
try {
client_1.subscribe(TOPIC, 1);
} catch (MqttSecurityException 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(TAG, "@onFailure: Connection Failed.");
}
});
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "Connection problems.");
}
}
}
public class clientCallBack implements MqttCallback {
@Override
public void connectionLost(Throwable e) {
// TODO Auto-generated method stub
Log.d(TAG, "@connectionLost: MQTT Server connection lost");
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "@deliveryComplete: sDelivery Completed");
}
@Override
public void messageArrived(String topic, MqttMessage message)
throws Exception {
// TODO Auto-generated method stub
Log.d(TAG, "@messageArrived: Message Arrived");
Log.d(TAG, "**********Topic: "+topic+"**********");
Log.d(TAG, "Message: "+message.toString());
Log.d(TAG, "QoS: "+message.getQos());
Log.d(TAG, "payload: "+message.getPayload());
Log.d(TAG, "isDuplicate? "+message.isDuplicate());
Log.d(TAG, "isRetained?"+message.isRetained());
}
}