-
Notifications
You must be signed in to change notification settings - Fork 925
Description
when the network instability,my mqtt connection while lost and the application will be kill probably.logs like below:
E/ProcessKiller( 229): Process com.example.myapplication (1405) has open file /storage/sdcard0/Android/data/com.example.myapplication/files/MqttConnection/MT8735303801b7da580ac585-tcplecbrokermapatcloudcom1883/.lck (deleted)
E/ProcessKiller( 229): Sending SIGKILL to process 1405
I try to open and close network to simulate the scene,but never success. it happens with probability.my code like below:
/**
- connect option
**/
public void connect() {
try {
if(isConnecting){
return;
}
if(client != null){
if (!client.isConnected()) {
client.connect(options,null,connectListener);
}
return;
}
isConnecting = true;
client = new MqttAndroidClient(mContext, SERVER_HOST, DeviceData.deviceNo);
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(username);
options.setPassword(userpsw.toCharArray());
options.setConnectionTimeout(100);
options.setKeepAliveInterval(20);
options.setAutomaticReconnect(true);
options.setWill(Mqttcmd.cmd_head + DeviceData.deviceNo + Mqttcmd.device2server_report, getLoginMessage().getPayload(), 0, true);
client.setCallback(new PushCallback());
client.connect(options, null, connectListener);
} catch (MqttException e) {
e.printStackTrace();
isConnecting = false;
if(callBack != null)callBack.onConnectException(e);
if(isNeedConnect && connect_try_times > 0 && isNetworkAvailable()) {
StaticData.handler.removeCallbacks(runnable);
StaticData.handler.postDelayed(runnable,60*1000);
}
}
}
/**
-
connect listener, reconnect when connect fail
**/
private IMqttActionListener connectListener = new IMqttActionListener() {
@OverRide
public void onSuccess(IMqttToken asyncActionToken) {
}@OverRide
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
exception.printStackTrace();
isConnecting = false;
if(callBack != null) callBack.onConnectFail(exception);
if(isNeedConnect && connect_try_times > 0 && isNetworkAvailable()) {
StaticData.handler.removeCallbacks(runnable);
StaticData.handler.postDelayed(runnable,60*1000);
}
}
};
/** -
connect callback,reconnect when connect lost
-
*/
public class PushCallback implements MqttCallback {
public void connectionLost(Throwable cause) {
if(callBack != null) callBack.onConnectLost(cause);
if(isNeedConnect && connect_try_times > 0 && isNetworkAvailable()) {
StaticData.handler.removeCallbacks(runnable);
StaticData.handler.post(runnable);
}
}
@OverRide
public void deliveryComplete(IMqttDeliveryToken token) {
}
@OverRide
public void messageArrived(final String topicName, final MqttMessage message)
throws Exception {
}}
/**
* reconnect function,reconnect once a minute
*/
private Runnable runnable = new Runnable() {
@OverRide
public void run() {
connect();
connect_try_times--;
}
};