Search code examples
androidandroid-service

Foreground Service or standard service?


I have Fragment which is basically a View that shows any incoming messages for a user. I want the create something that will check every 5 seconds for any new messages, and if found will append them to my ListView which holds the messages. My question is, from what I have read, a Service is the way to go with this. However, since I will be communicating with the app from this service I'd like to know which service I should use.

Should I be using a Foreground service, or just a standard Service?

My goal is that where ever the user is in my app, I will be able to receive some notification that a new message has come through and then perform a function when that happens.

I want to code this properly and according to best practices.


Solution

  • If you just want to call a method on your service when user is in your app, you just need to use a sticky service, but if you want to call this method even when user swipe your app away from recent apps you should use not_sticky service.

    Foreground service are most used for cases that u don't want your task stop even for a second after swiping your app from recent apps e.g. playing music in background.

    But in your case the best choice is to use postDelayed() and set 5 seconds delay for it and get rid of service.