简体   繁体   English

在Android中的onCreate方法之外调用mqtt setCallback方法

[英]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. 我正在为我的Android APP使用paho mqtt libray。出于某种目的,我想在onCreate方法外调用setCallback方法。在onCreate内它工作良好,但在onCreate方法外它不起作用。我想为此创建单例类MQTT连接。我无法做到这一点。 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: 您可以按以下方式创建MqttHelper类:

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. 然后,您需要调用MqttHelper类,并将应用程序的上下文作为构造函数参数传递。 Simply, call startMqtt() method described below from your activity. 只需从您的活动中调用下面描述的startMqtt()方法。

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) {

         }
     });
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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