IMqttActionListener 回调多次



我想创建一个在后台运行的服务。
这看起来不错,但是当RunMqttProcess再次调用成功方法时,会多次调用。
在第一个 -> 发布一条消息
中,第二个 ->发布两条消息
...
第四 ->发布 4 条消息。

位置场景只有一个元素。

public class MqttService {
static IMqttActionListener actionListener = null;
public static boolean RunMqttProcess(final Context context, final Config config, final Location location, final ArrayList<LocationScene> locationScenes) {
String clientId = "ThoMi_" + getMacAddress();
HashMap mqttConfig = config.getMqttConfig();
Log.d(TAG, "clientId: " + clientId);
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(context, mqttConfig.get("url").toString(), clientId);
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName(mqttConfig.get("userName").toString());
mqttConnectOptions.setPassword(mqttConfig.get("password").toString().toCharArray());
mqttConnectOptions.setCleanSession(true);
for (final LocationScene locationScene : locationScenes) {final Double meter = Convert.measure(location.getLatitude(), location.getLongitude(), locationScene.getLatitude(), locationScene.getLongitude());
Boolean conditionTime = checkConditions();
//......
if (conditionTime && meter < locationScene.getRadius() && 0 == locationScene.getControlled() && !locationScene.getDisabled()) {
locationScene.setControlled(System.currentTimeMillis());
LocationSceneDAO dao = DAOFactory.createLocationSceneDAO(context);
dao.editLocationScene(locationScene);
actionListener = null;
actionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
try {
for (HashMap<String, String> device : locationScene.getDevices()) {
MqttMessage message = new MqttMessage();
message.setRetained(false);
message.setPayload(device.get("message").getBytes());
mqttAndroidClient.publish(device.get("topic"), message);
if (!mqttAndroidClient.isConnected()) {
Log.d(TAG, mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
}
}
} catch (MqttException e) {
Log.d(TAG, "[postMQTT]:  Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "[postMQTT]: Failed to connect to " + config.getMqttConfig().get("url"));
}
};
mqttAndroidClient.connect(mqttConnectOptions, null, actionListener);
}
}
if (mqttAndroidClient.isConnected()) {
mqttAndroidClient.disconnect();
}
} catch (MqttException e) {
Log.d(TAG, e.getCause().getMessage());
}
return true;
}
}

可能有什么问题?

可能会晚了,但请确保您正在断开 MQTT 客户端的连接。我的问题是每次我触发应用程序时都会再次建立连接,因此多个客户端在同一 clientID 上连接。

最新更新