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

时间:2018-03-15 12:03:44

标签: android mqtt

我正在为我的Android APP使用paho mqtt libray。我想在 onCreate 方法之外调用 setCallback 方法用于特定目的。在onCreate中它运行良好,但是在 onCreate 方法之外,它不起作用。我想为这个MQTT连接制作单例类。我无法做到这一点。请建议我如何做到这一点。我的代码如下:

`

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();
             }

         }

    }

`

1 个答案:

答案 0 :(得分:0)

您可以将 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();
        }
    }
}

然后你需要调用MqttHelper类并将应用程序的上下文作为构造函数参数传递。只需从您的活动中调用下面描述的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) {

         }
     });
 }