Android Paho Mqtt在wifi重新连接后不会重新连接

Android Paho Mqtt在wifi重新连接后不会重新连接,android,android-service,alarmmanager,mqtt,paho,Android,Android Service,Alarmmanager,Mqtt,Paho,我正在使用mqtt android客户端来传输位置。在internet连接断开之前,此功能正常工作。mqtt客户端未按预期重新连接。我应该如何确保paho mqtt重新连接到代理。 我想强制mqtt客户机重新连接到代理,并在连接返回时继续发布位置 下面是我的代码 public class MqttClientHelperService2 extends Service { private MqttAndroidClient mqttAndroidClient; Broadcast

我正在使用mqtt android客户端来传输位置。在internet连接断开之前,此功能正常工作。mqtt客户端未按预期重新连接。我应该如何确保paho mqtt重新连接到代理。 我想强制mqtt客户机重新连接到代理,并在连接返回时继续发布位置

下面是我的代码

public class MqttClientHelperService2 extends Service {
    private MqttAndroidClient mqttAndroidClient;
    BroadcastReceiver broadcastReceiver;
    private final String SERVER_URL = "tcp://000.102.110.**:1883";
    private final String CLIENT_ID = "client_id";
    private final String MQTT_TOPIC = "livelocations/local";
    LiveLocation liveLocation;

    @Override
    public void onCreate() {
        super.onCreate();
        Thread newThread = new Thread(){
            public void run(){
                init();
            }
        };

        newThread.start();

        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_LOW);

            ((NotificationManager) Objects.requireNonNull(getSystemService(Context.NOTIFICATION_SERVICE))).
                    createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("")
                    .setSmallIcon(R.mipmap.ic_launcher).build();

            startForeground(1, notification);
        }
    }

    private void init() {
        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), SERVER_URL, CLIENT_ID);
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }


        });
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        liveLocation= new LiveLocation(
                intent.getIntExtra("driver_id", 0),
                intent.getDoubleExtra("latitude", 0),
                intent.getDoubleExtra("longitude", 0),
                "");
        connectMqtt();
        return START_STICKY;
    }


    private MqttConnectOptions getMqttOptions(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        return mqttConnectOptions;
    }

    private void connectMqtt() {
        try {
           IMqttToken iMqttToken =  mqttAndroidClient.connect(getMqttOptions());
           iMqttToken.setActionCallback(new IMqttActionListener() {
               @Override
               public void onSuccess(IMqttToken asyncActionToken) {
                    Log.e("phanuel-log", "connecting ......." + Calendar.getInstance().getTime());
                   publishToServer(liveLocation);
               }

               @Override
               public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.e("phanuel-log-error", "connection error");
               }
           });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        if(mqttAndroidClient != null){
            try {
                mqttAndroidClient.unregisterResources();
                mqttAndroidClient.close();
                mqttAndroidClient.disconnect();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        unregisterReceiver(broadcastReceiver);
        broadcastReceiver = null;
        super.onDestroy();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        assert  connectivityManager != null;
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }

    void publishToServer(final LiveLocation location) {
        try {
            if (location.getDriverId() > 0){
                mqttAndroidClient.connect(getMqttOptions(), null, new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        JSONObject locationJsonObject = new JSONObject();
                        try {
                            locationJsonObject.put("driverId", location.getDriverId());
                            locationJsonObject.put("driverLatitude", location.getLatitude());
                            locationJsonObject.put("driverLongitude", location.getLongitude());
                            locationJsonObject.put("driverTimeStamp", Calendar.getInstance().getTime());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        MqttMessage mqttMessage = new MqttMessage();
                        mqttMessage.setPayload(locationJsonObject.toString().getBytes());
                        mqttMessage.setQos(0);
                        mqttMessage.setRetained(false);

                        try {
                            mqttAndroidClient.publish(MQTT_TOPIC, mqttMessage);
                        }catch (MqttException e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        Log.e("mqtt-client", "Failed to connect");
                        Log.e("mqtt-cleint", exception.toString());
                    }
                });
            }
        } catch (MqttException e){
            e.printStackTrace();
        }
    }
}

有多种方法可以处理您的场景

  • 如果您只使用mqtt从android端发布,那么您可以 在中发布之前调用init()函数(连接到mqtt服务器) mqtt。消息发布后,您可以断开与mqtt服务器的连接
  • 如果您总是需要活动的mqtt连接,那么每当mqtt连接断开时 然后调用connectionLost方法。您可以使用此方法重新连接
  • 您可以让线程不断检查mqtt连接是否处于活动状态,如果断开连接,您可以重新连接