Android Question MQTT client as service (please help...)

giggetto71

Active Member
Licensed User
Longtime User
Hi guys,
after weeks of coding my new app I am back at square 0 so I am asking for some help.
before posting any code (of course I don't want you to debug my terrible code..), I need to understand if I am following the right approach. Here's what I have. the app start with a simple UI where the broker parameters are set. then from the UI there is a botton that starts a service which connects to the broker and receives all the messages regardless if the UI app is visible or not. the messages are stored in internal map.
When I click thew start service button the code calls a "StartService". In the Service create I have Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS (in my mind the service must run always until the user stops it). then in the service start I call the Service.StartForeground(0, Notification1) and connect to the MQTT broker successfully.

Conceptually it looks actually quite simple but I am sure I am making some fundamental mistakes because this is what happens:

- PROBLEM1: if I exit the UI the service apparently keeps running (as I see the icon) but after some time (around a minute) it stops (it does not stop if I keep the app open)
-PROBLEM2: when the UI is on the MQTT messages are received without issues when the UI is off the behavior is random and sometimes messages are received sometimes they are not (which of course gets me nut..), the funny thing is that if I open the UI the messages start flowing again..

Do you think a service started as AutomaticForegroundMode can act as mqtt client and keep receiving messages while the UI app is not running?
thanks!
 

giggetto71

Active Member
Licensed User
Longtime User
sorry guys. I think I found the issue. basically I had StartForeground in the Service start instead of the Service create. the service now keeps running.
 
Upvote 0
Top