MQTT在多次调用onCreate时创建多个连接

时间:2017-02-07 22:30:53

标签: java android mqtt paho

我正在使用Paho Android MQTT Client创建即时消息系统。它的实现按预期工作,但我遇到了这些错误。

我在Connection Class的{​​{1}}中调用onCreate(这也要求创建与代理的连接)。

现在的问题是,假设我在MainActivity Class并且我按回来从MainActivity Class转移到另一个活动,我后来回到MainActivity Class,另一个将创建代理连接。这意味着无论何时发布单个消息,客户端都将收到两次消息。

MainActivity.java:

公共类MainActivity扩展了AppCompatActivity {

MainActivity Class

}

Connection.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_intera);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    dbHelper = DatabaseManager.getInstance(context);
    //mRecyclerView = (RecyclerView) findViewById(R.id.history_recycler_view);

    connections = new Connections();
    connections.createConnectionForPublishing(context);

}


@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("LOG: Service destroyed");
}

我是MQTT的新手,如果有人可以提供帮助,我会很高兴。提前致谢

3 个答案:

答案 0 :(得分:2)

然后,如果您不想多次建立连接,则必须将其设置为单例,以便只建立一个连接类实例和一次连接。

所以你的代码将成为:

<强> MainActivity.java:

public class MainActivity extends Activity {

    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.chat_intera);

        Connection connection = Connection.getInstance (getApplicationContext ());
    }

    // ....
}

<强> Connection.java

public class Connection {

    private       static Connection          connInst;
    private       static boolean             connected;

    private       static MqttAndroidClient   mqttAndroidClient;
    private       static IMqttActionListener mqttActionListener;
    private final static MqttConnectOptions  mqttConnectOptions = new MqttConnectOptions (); 
    static {
        mqttConnectOptions.setMqttVersion (MqttConnectOptions.MQTT_VERSION_3_1_1);
        mqttConnectOptions.setAutomaticReconnect (true);
        mqttConnectOptions.setCleanSession (false);
    }

    private Connection (Context context) {
        //Instantiate the mqtt android client class
        mqttAndroidClient = new MqttAndroidClient (context.getApplicationContext (), serverUri, clientId);

        mqttAndroidClient.setCallback (new MqttCallbackExtended () {

            @Override
            public void connectComplete (boolean reconnect, String serverURI) {
                connected = true;
                if (reconnect) {
                    System.out.println ("Reconnected to : " + serverURI);
                } else {
                    System.out.println ("Connected to: " + serverURI);
                }
            }

            @Override
            public void connectionLost (Throwable cause) {
                connected = false;
                System.out.println ("The Connection was lost.");
            }

            @Override
            public void messageArrived (String topic, final MqttMessage message) throws Exception {
                System.out.println ("Message received and Arrived");
            }

            @Override
            public void deliveryComplete (IMqttDeliveryToken token) {
                System.out.println("Message Delivered");
            }
        });

        mqttActionListener = new IMqttActionListener () {

            @Override
            public void onSuccess (IMqttToken asyncActionToken) {
                System.out.println ("BROKER CONNECTED");

                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) {
                System.out.println ("Failed to connect to: " + serverUri);
            }
        });
    }

    public static Connection getInstance (Context context) {
        if (connInst == null) {
            connInst = new Connection (context);
        }
        createConnectionIfNeeded (context);

        return connInst;
    }

    private static void createConnectionIfNeeded () {
        if (connected) {
            return;
        }

        try {
            mqttAndroidClient.connect (mqttConnectOptions, null, mqttActionListener);

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

    // ...
}

答案 1 :(得分:1)

我不确定,但我认为可能是空检查可以帮助

if (connection == null){
   connections = new Connections();
   connections.createConnectionForPublishing(context);
}

答案 2 :(得分:0)

我建议您使用Android onPause()

设置标记

https://developer.android.com/reference/android/app/Activity.html#onPause()

然后使用onCreate()代替onResume()来启动MQTT连接,但首先检查onPause()标志。

您可能还需要在onPause()onDestroy()中关闭连接。查看Android应用程序/活动的生命周期以获取更多信息。