我正在开发的应用程序中实现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);
}
解决方法
我知道这是对这个问题的一个迟到的答案,但我想分享我所做的,因为它可以帮助某人.
我创建了自己的服务来管理与代理的连接,并始终为每个Android设备维护一个连接的实例.
重申解决方案的功能:
Key features of this solution:
>只要服务还活着,服务就会维护一个实例.
>如果服务被终止,Android会重新启动它(因为START_STICKY)
>设备启动时可以启动服务.
>服务在后台运行,并始终连接以接收通知.
>如果服务处于活动状态,再次调用startService(..)将触发其onStartCommand().在此方法中,我们只需检查此客户端是否已连接到代理,并在需要时连接/重新连接.
查看完整详细的答案here.