当多次调用onCreate时,MQTT创建多个连接 [英] MQTT Creates Multiple connections when onCreate is called more than once
问题描述
我正在使用Paho Android MQTT Client创建即时消息传递系统.它的实现按预期工作,但是我遇到了这些错误.
I am creating an instant messaging system using Paho Android MQTT Client. Its implementation works as expected, however I am facing these errors.
我在MainActivity Class
的onCreate
中呼叫Connection Class
(这也要求创建与代理的连接).
I call the Connection Class
( This also calls for the creation of the connection to the broker) in the onCreate
of the MainActivity Class
.
现在的问题是,假设我在MainActivity Class
上,然后按回车键从MainActivity Class
转到另一活动,然后又回到MainActivity Class
,则将创建另一个代理连接.这意味着每发布一条消息,客户端都会收到两次消息.
Now the problem is that, assuming I am on the MainActivity Class
and I press back to move from the MainActivity Class
to another activity, and I later come back to the MainActivity Class
, another broker connection will be created. This will mean that anytime a single message is published, the client will receive the message twice.
MainActivity.java:
公共类MainActivity扩展了AppCompatActivity {
public class MainActivity extends AppCompatActivity {
@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");
}
}
Connection.java
public class Connection {
public void createConnectionForPublishing (final 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) {
if (reconnect) {
System.out.println ("Reconnected to : " + serverURI);
} else {
System.out.println ("Connected to: " + serverURI);
}
}
@Override
public void connectionLost (Throwable cause) {
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");
}
});
final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions ();
mqttConnectOptions.setMqttVersion (MqttConnectOptions.MQTT_VERSION_3_1_1);
mqttConnectOptions.setAutomaticReconnect (true);
mqttConnectOptions.setCleanSession (false);
try {
mqttAndroidClient.connect (mqttConnectOptions, null, 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);
}
});
} catch (MqttException ex) {
ex.printStackTrace ();
}
}
// ...
}
我是MQTT的新手,如果有人可以提供帮助,我将感到非常高兴.预先感谢
I am new to MQTT, I would be glad if somebody can help. Thanks in advance
推荐答案
然后,如果您不想多次建立连接,则必须使其成为单例,以仅具有一个连接类实例和一个连接类实例.建立时间连接.
Then if you don't want to establish the connection multiple times you'll have to make it as singleton to have only 1 instance of the connection class and one time connection established.
因此您的代码将变为:
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 ();
}
}
// ...
}
这篇关于当多次调用onCreate时,MQTT创建多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!