10

I'm currently build an chat app using XMPP. I've created a service to handle the connection and incoming messages, adding the different listeners needed.

The problem is, however, whenever the activity calls unbind on the service (e.g. when the activity is paused or stopped when the user puts the app in the background) the service gets destroyed, even though it has listeners inside it (such as a chat listener, message listener, etc..)

How can I keep my service alive to be able to receive messages when the app is in the background? I read that using a foreground service is quite frowned upon, so I'd rather avoid that if possible.

Pat
  • 1,193
  • 1
  • 11
  • 36

1 Answers1

16

I actually had this when developing my app recently.

The trick is to start the Service on its own and then bind to it using the Intent. When you unbind from it, the Service will still continue running.

Intent i = new Intent(this, DataService.class);
startService(i); 
bindService(i, this, Context.BIND_AUTO_CREATE);
Sufian
  • 6,405
  • 16
  • 66
  • 120
CarbonAssassin
  • 855
  • 12
  • 24
  • Well, this is correct, but then you don't have the opportunity anymore that the service gets automatically destroyed after unbind somewhere else in the code. You have to stop it manually then. – JacksOnF1re Jan 05 '15 at 17:25
  • Great Solution! I've always wondered if it will work to use normal start with bind\unbind, I couldn't find it as a separate question, +1 fort that. – Majed DH Nov 15 '17 at 17:52
  • 2
    That does not work anymore. Service gets still destroyed. For newer SDKs a foreground service is required. see here https://stackoverflow.com/a/45047542/617889 – oleh Jan 08 '21 at 15:25