Android 持久的 MQTT 连接
Android Long Lasting MQTT connection
我需要在应用程序关闭后启动连接 - onDestroy() 被调用并且应用程序不再可见。
MainActivity 在
中启动一个服务
@Override
public void onCreate(Bundle savedInstanceState){
if(savedInstanceState == null) {
startService(new Intent(MainActivity.this, MqttService.class));
}
服务通过 AsyncTask 启动 MQTT 连接。
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Notification note = createNotification();
//startForeground(20, note);
new MqttTask().execute(CONNECT_RETRIES);
return START_REDELIVER_INTENT;
}
只要应用程序保持活动状态,MQTT 连接就会保持活动状态,因为服务也已准备就绪。该服务还实现了一些我需要使用的回调方法,具体是:
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
我的目标是即使在应用程序关闭时也允许连接处于活动状态,以便用户可以通过连接接收消息而无需打开应用程序。我想这个想法是在应用程序被销毁时重新连接
我尝试过的:
1) 我不喜欢这个解决方案,因为虽然它有效,但它为用户提供了一个恼人的通知
startForeground(23, createNotification());
2) 我尝试使用 AlarmManager 在特定时间间隔调用 startService(MqttService.class),但根据最佳实践,不建议这样做。
3) 我查看了 https://developer.android.com/training/sync-adapters/creating-sync-adapter.html 但这似乎更像是 "connect-once" 而不是持续和已建立的连接。
有什么想法吗?
您是否查看过 Paho Android 服务而不是编写自己的服务?
https://eclipse.org/paho/clients/android/
这应该 运行 在后台并保持 运行ning 直到它被明确杀死。
此外,如果您想继续使用自己的服务,那么您应该查看上一个问题。
How to restart a killed service automatically?
我需要在应用程序关闭后启动连接 - onDestroy() 被调用并且应用程序不再可见。
MainActivity 在
中启动一个服务@Override
public void onCreate(Bundle savedInstanceState){
if(savedInstanceState == null) {
startService(new Intent(MainActivity.this, MqttService.class));
}
服务通过 AsyncTask 启动 MQTT 连接。
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Notification note = createNotification();
//startForeground(20, note);
new MqttTask().execute(CONNECT_RETRIES);
return START_REDELIVER_INTENT;
}
只要应用程序保持活动状态,MQTT 连接就会保持活动状态,因为服务也已准备就绪。该服务还实现了一些我需要使用的回调方法,具体是:
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
我的目标是即使在应用程序关闭时也允许连接处于活动状态,以便用户可以通过连接接收消息而无需打开应用程序。我想这个想法是在应用程序被销毁时重新连接
我尝试过的:
1) 我不喜欢这个解决方案,因为虽然它有效,但它为用户提供了一个恼人的通知
startForeground(23, createNotification());
2) 我尝试使用 AlarmManager 在特定时间间隔调用 startService(MqttService.class),但根据最佳实践,不建议这样做。
3) 我查看了 https://developer.android.com/training/sync-adapters/creating-sync-adapter.html 但这似乎更像是 "connect-once" 而不是持续和已建立的连接。
有什么想法吗?
您是否查看过 Paho Android 服务而不是编写自己的服务?
https://eclipse.org/paho/clients/android/
这应该 运行 在后台并保持 运行ning 直到它被明确杀死。
此外,如果您想继续使用自己的服务,那么您应该查看上一个问题。
How to restart a killed service automatically?