我正在开发一个应用程序中实现Paho MQTT Android服务。在测试了Paho提供的示例应用程序之后,我发现我想更改一些事情。
https://eclipse.org/paho/clients/android/
一旦应用程序完全关闭,应用程序服务似乎就会关闭。我希望即使在应用程序关闭后也能保持服务运行,如果有更多消息进入。我也正在寻找一种方法,以便在收到新消息后针对特定活动打开应用程序。
这是消息到达时调用的回调之一,我试图实现一个简单的startActivity来打开特定的活动,但是如果应用程序已关闭/不再运行,它将无法正常工作。
如果有人使用过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);
}
我知道这是该问题的较晚答案,但是我想分享一下我所做的事情,因为这可能会对某人有所帮助。
我创建了自己的服务器Service
来管理与代理的连接,并始终为每个android设备维护一个连接的实例。
重申该解决方案的功能:
该解决方案的主要特点:
startService(..)
再次调用将触发它onStartCommand()
。在这种方法中,我们仅检查此客户端是否已连接到代理,并根据需要连接/重新连接。在此处查看完整详细的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句