1

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?

Teddy
  • 21
  • 3
  • 1
    Read this answer: https://stackoverflow.com/questions/9740593/android-create-service-that-runs-when-application-stops?rq=1 – Stanojkovic Jun 03 '17 at 15:20

1 Answers1

1

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!