简体   繁体   中英

Calling mqtt setCallback method outside the onCreate method in Android

I am using paho mqtt libray for my android APP.I want to call setCallback method outside the onCreate method for certain purpose.Inside the onCreate it works well, but outside of onCreate method it does not work.i want to make singleton class for this MQTT connection.I am unable to to this. Please suggest me how to do this.My code is given below :

`

package com.example.tausif.mushroomv2;

        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.widget.Toast;
        import org.eclipse.paho.android.service.MqttAndroidClient;
        import org.eclipse.paho.client.mqttv3.IMqttActionListener;
        import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
        import org.eclipse.paho.client.mqttv3.IMqttToken;
        import org.eclipse.paho.client.mqttv3.MqttCallback;
        import org.eclipse.paho.client.mqttv3.MqttClient;
        import org.eclipse.paho.client.mqttv3.MqttException;
        import org.eclipse.paho.client.mqttv3.MqttMessage;

        public class Main2ActivityTest extends AppCompatActivity {

        MqttAndroidClient client;

        String clientId;

        static String host = "tcp://182.133.112.204:1883";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2_test);


            client.setCallback(new MqttCallback() {




                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {

                }

                @Override
                public void connectionLost(Throwable cause) {
                    establish();


                }

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



                }

            });


        }


        public void establish() {
            clientId = MqttClient.generateClientId();
            client = new MqttAndroidClient(this.getApplicationContext(), host, clientId);

            try {
                IMqttToken token = client.connect();
                token.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {



                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable 
                    exception) {

                    }
                });
            } catch (MqttException e) {
              e.printStackTrace();
             }

         }

    }

`

You can create a MqttHelper class as:

public class MqttHelper {
    public MqttAndroidClient mqttAndroidClient;

    final String host = "tcp://182.133.112.204:1883";
    final String clientId = MqttClient.generateClientId();

    public MqttHelper(Context context) {
        mqttAndroidClient = new MqttAndroidClient(context, host, clientId);

        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverUri) {

            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

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

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        connect();
    }

    public void setCallback(MqttCallbackExtended callback) {
        mqttAndroidClient.setCallback(callback);
    }

    private void connect() {

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, 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);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Failed to connect to: " + host + exception.toString());
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }
}

Then you need to call MqttHelper class and pass application's context as constructor parameter. Simply, call startMqtt() method described below from your activity.

public void startMqtt(){
     mqttHelper = new MqttHelper(getApplicationContext());
     mqttHelper.setCallback(new 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) {

         }
     });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM