我正在开发一个应用程序,需要使用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);
}