Teddy
Teddy

Reputation: 21

How to keep a service running when I close the application?

My application need a service running in background even when the app is closed, i've just implemented START_STICKY to prevent the OS close it, but when i manually close the application the service stop running and i don't know how to keep it alive without using startforeground.

It is an istant messaging application similar to Whatsapp and Telegram, so my aim it to implement a sort of push notification system.

So the main question is: How can i keep the service alive when the user manually close the app?

Upvotes: 1

Views: 812

Answers (1)

James Semaj
James Semaj

Reputation: 31

After finding there's not any really satisfactory answer to this on StackOverflow or elsewhere I decided to research the (current, 2017) definitive solution.

Here it is:

https://github.com/JamesSmartCell/PersistentWidgetTask.git

This is a demo that shows how to implement a persistent background task that doesn't get shut down, that also shows a very simple implementation of a button in a widget too, another very common design that doesn't receive a lot of good answers.

I looked at a lot of little demos across the internet, the key to this was on the excellent Vogella website here:

http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html

The breakdown is:

  1. You need to use JobScheduler not AlarmManager
  2. You need to create a JobService to receive the scheduled job, then call your background service from the JobService onStartJob
  3. In your AndroidManifest file you need to specify:

    android:permission="android.permission.BIND_JOB_SERVICE"

I hope this saves someone who is still searching for the answer a lot of time!

Upvotes: 1

Related Questions