0

I have a foreground service started by startForeground() and onStartCommand reurns START_STICKY. I want to run it all the day, but it gets stopped when I play games or manually increase RAM usage by a “Fill RAM Memory” app from Google Play. (Even if it is killed, the notification is still showing.) How can I fix it?

EDIT: Or is there a better way? The service runs 3 threads which contain an infinite loop with some internet calls and then 20 min or 10 min (depends on situation) sleep. Maybe an AlarmManager or something like that.

EDIT 2: My tablet has Android 4.4 (API 19), so I can't use JobScheduler. I think I'll use AlarmManager and It'll be ok. (I found AlarmManagerExample here: https://github.com/rakeshcusat/Code4Reference)

shy_potato
  • 137
  • 1
  • 9
  • `"I want to run it all the day"` - what for? whats the reason behind? – pskink Feb 11 '18 at 08:00
  • I just edited the question. I do some internet calls in it. – shy_potato Feb 11 '18 at 08:01
  • good, you are answering your own questions quite well... also `android sync adapter` and [FCM](https://en.wikipedia.org/wiki/Firebase_Cloud_Messaging) (new version of GCM), but yes `AlarmManager` is a good solution to start from.... – pskink Feb 11 '18 at 08:10

1 Answers1

1

Make sure that you have implemented the Foreground service correctly. When it’s alive you’ll have a special notification in notification bar that will let user know that your service is working and consuming resources. Still in some situations it can be killed by the system. For possible problems see Foreground service being killed by Android

As an alternative solution you could try JobScheduler. It allows the system to schedule your tasks more efficiently based on some conditions (network availability for instance). It also supports periodic jobs. Usually one should prefer it over AlarmManager. See https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

For older Android versions Firebase JobDispatcher can be used https://github.com/firebase/firebase-jobdispatcher-android

algrid
  • 5,600
  • 3
  • 34
  • 37