gpt4 book ai didi

android - Paho MQTT Android 服务问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:57 28 4
gpt4 key购买 nike

我正在开发的应用程序中实现 Paho MQTT Android 服务。在测试了 Paho 提供的示例应用程序后,我发现有一些地方我想更改。

https://eclipse.org/paho/clients/android/

一旦应用程序完全关闭,应用程序服务似乎就关闭了。即使在应用程序关闭后,如果收到更多消息,我也想保持服务运行。我还在寻找一种方法,在收到新消息后将应用程序打开到特定 Activity 。

这是消息到达时调用的回调之一,我尝试实现一个简单的 startActivity 来打开特定 Activity ,但如果应用关闭/不再运行.

如果有人使用过 PAHO MQTT Android 服务,是否有特定的方法可以在应用程序关闭时防止服务停止,以及如何在消息到达时重新打开应用程序?

    /**
* @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String,
* org.eclipse.paho.client.mqttv3.MqttMessage)
*/
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {

// Get connection object associated with this object
Connection c = Connections.getInstance(context).getConnection(clientHandle);

// create arguments to format message arrived notifcation string
String[] args = new String[2];
args[0] = new String(message.getPayload());
args[1] = topic + ";qos:" + message.getQos() + ";retained:" + message.isRetained();

// get the string from strings.xml and format
String messageString = context.getString(R.string.messageRecieved, (Object[]) args);

// create intent to start activity
Intent intent = new Intent();
intent.setClassName(context, "org.eclipse.paho.android.service.sample.ConnectionDetails");
intent.putExtra("handle", clientHandle);

// format string args
Object[] notifyArgs = new String[3];
notifyArgs[0] = c.getId();
notifyArgs[1] = new String(message.getPayload());
notifyArgs[2] = topic;

// notify the user
Notify.notifcation(context, context.getString(R.string.notification, notifyArgs), intent,
R.string.notifyTitle);

// update client history
c.addAction(messageString);

Log.e("Message Arrived", "MESSAGE ARRIVED CALLBACK");

// used to open the application if it is currently not active
Intent i = new Intent(context, ConnectionDetails.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("handle", clientHandle);
context.startActivity(i);


}

最佳答案

虽然这似乎不是问题的完整解决方案,但我会发布我的解决方法以防它对某人有所帮助。

对我来说,当用户将应用从最近使用的应用列表中滑出时,问题就开始了。如前所述 here这样的操作不仅会终止 Activity,还会终止整个进程,包括 MqttService。然后如线程中所述,Android 识别出您的服务应该重新启动并安排重新启动已终止的服务。但是,这并不意味着连接恢复,因为所有连接都绑定(bind)到该 Activity 。

因此,除非您找到消除服务停止问题的方法,否则当用户决定退出应用时,您肯定会失去与代理的连接。

但这并不是世界末日,因为我们可以在失去连接后轻松重新连接。问题是,这次我们没有执行所需操作的 Activity 。您必须修改 Paho Android 服务库的源代码,或者以更简单的方式创建另一个服务。

所有连接都将在这个新服务中进行,任何希望连接的 Activity 都应该与这个服务进行通信。这样做的好处是我们可以使服务具有粘性,即使用户滑动我们的应用并将其杀死,它也会立即重新启动,我们只需重新连接即可恢复。

作为这个非常简单的服务的演示:

public class MessagingService extends Service {
private static final String TAG = "MessagingService";
private MqttAndroidClient mqttClient;
String deviceId;



@Override
public void onCreate() {
}
private void setClientID() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
deviceId = wInfo.getMacAddress();
if (deviceId == null) {
deviceId = MqttAsyncClient.generateClientId();
}
}

public class MsgBinder extends Binder {
public MsgServ getService() {
return MsgServ.this;
}
}

public void doConnect(){
// Using some of the Paho sample app classes
String server = ConfigClass.BROKER_URI;
MemoryPersistence mem = new MemoryPersistence();
mqttClient = new MqttAndroidClient(this,ConfigClass.BROKER_URI,deviceId,mem);
MqttConnectOptions conOpt = new MqttConnectOptions();
String clientHandle = server + deviceId;
Connection con = new Connection(clientHandle, deviceId, ConfigClass.BROKER_ADDRESS,
ConfigClass.BROKER_PORT, this, mqttClient, false);
conOpt.setCleanSession(false);
conOpt.setConnectionTimeout(ConfigClass.CONN_TIMEOUT);
conOpt.setKeepAliveInterval(ConfigClass.CONN_KEEPALIVE);
conOpt.setUserName("testclient");
conOpt.setPassword("password".toCharArray());
String[] actionArgs = new String[1];
actionArgs[0] = deviceId;
final ActionListener callback =
new ActionListener(this, ActionListener.Action.CONNECT, clientHandle,
actionArgs);
mqttClient.setCallback(new MqttCallbackHandler(this, clientHandle));
mqttClient.setTraceCallback(new MqttTraceCallback());
con.addConnectionOptions(conOpt);
Connections.getInstance(this).addConnection(con);
try {
mqttClient.connect(conOpt, null, callback);
Log.d("Con", "Connected");
} catch (MqttException e) {
Log.d("Con", "Connection failed");
e.printStackTrace();
}
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
doConnect();
return START_STICKY;
}

}

服务器日志:

1433455371: New client connected from 192.168.2.5 as ed:0a:2b:56:b5:45 (c0, k30, u'testclient').
1433455371: Sending CONNACK to ed:0a:2b:56:b5:45 (1, 0)
1433455375: Socket error on client ed:0a:2b:56:b5:45, disconnecting.
1433455377: New connection from 192.168.2.5 on port 1883.
1433455377: Client ed:0a:2b:56:b5:45 disconnected.
1433455377: New client connected from 192.168.2.5 as ed:0a:2b:56:b5:45 (c0, k30, u'testclient').
1433455377: Sending CONNACK to ed:0a:2b:56:b5:45 (1, 0)

如您所见,一旦我关闭应用程序并且服务被终止,它会重新启动重新连接并保持 Activity 状态,然后才找到。从这里开始,您应该可以完成剩下的工作。也许使用您新收到的消息创建一个通知,这将打开应用程序。请记住在保证保持连接的新创建服务中执行所有操作。

关于android - Paho MQTT Android 服务问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28543569/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com