1

I would like to start my foreground service when my application is closed.

I tryed OnStop() but it's not a good idea for me because it can trigger multiple times and i which it to run only one instance.

I tryed OnDestroy() but it's simply doesn't trigger since i'm only using one activity in my whole app and most of time it is being kill with the SWIPE.

Is there a way i can detect when my application being kill or close ?

Thanks!

Pilouk
  • 1,267
  • 1
  • 18
  • 36

2 Answers2

1

Only one instance of the service will run no matter how many times you start it. Each time a client starts the service the onStartCommand method fires. return Service.START_STICKY; to have your service stay running in the back ground after your app exits. But be warned if things get busy and the phone needs memory your service will be killed and you'll have to restart it like @Onur suggests with a conservative periodic AlarmManager intent.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // the service is started so after all clients are unbound it stays
    // running
    return Service.START_STICKY;
}
danny117
  • 5,581
  • 1
  • 26
  • 35
  • I use foreground because i want it to run even if my app is closed put the flag start sticky is not enough. The problem with onStartcommand it's that like you said it's being fire multiple time. I may use the onCreate method only. – Pilouk May 30 '14 at 12:08
0

You can add your services description in manifest.xml stopWithTask="false" and in your sevice override the onTaskRemoved (Intent rootIntent) to know when activity that started the service is stopped for API level 14 and later.

Or you can set an alarm for some periods to check if your application is still running using AlarmManager. You should be careful with this tho, because it might consume battery based on the period you choose.

Onur
  • 5,617
  • 3
  • 26
  • 35
  • i will look through this thanks, i find it quite sad that there is not a better way like some basic closing event on the application... Feel like i always have to battle on the android system. – Pilouk May 30 '14 at 12:10
  • 1
    I did same step but service could not started, can you please help me? – Hiren Patel Mar 25 '17 at 04:12
  • @HirenPatel been a while since I looked into android, I'm not aware of recent api changes but I can try. Any error log or something? – Onur Mar 25 '17 at 09:19