Start service when the application exit (or is killed) - android

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!

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;
}

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.

Related

Android: Keep service running, stop when app closed (removed from app tray)

I have a location service which I want to run at all times when the app is in the foreground, or in the background, but to stop when the app is closed (removed from the app tray)
My solution has been to start the service using START_NOT_STICKY and this seems to work, but I'm concerned by what the service documentation says about this command
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
So it seems that Android may kill off services when memory is low, and if using START_NOT_STICKY the service will not be restarted.
I tried using START_STICKY but this keeps the service running even after the app is closed.
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
Code here if it matters:
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (intent != null) {
extras = intent.getExtras();
// takes the messenger object and makes it local so when the messagereceiver sends an intent here, it won't overwrite the extras object
// and get rid of the messenger. Otherwise, getting an update from the notification controls would null out the messenger object
if (intent.hasExtra("MESSENGER")) {
Timber.e("MESSENGER ");
messenger = (Messenger) extras.get("MESSENGER");
}
}
return START_NOT_STICKY;
}
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
I'm not sure what "app tray" you're referring to or what exactly you mean by "closed" (Android apps are not things that are "closed", per se.
But, from your description, I'd think you want to do something like:
Start your Service when the user starts your app and bind to while the activity is in the foreground
If your activity is paused (or stopped), unbind from the service and start a foreground notification to keep the service alive and the user aware that it's still running
Instead of trying to detect when the app is "closed", which you can't really do, attach a "cancel" action to the foreground notification so the user can cancel it whenever they want
If that doesn't solve your issue, please elaborate on your use case and why you want to do this. I or others may be able to provide more / better / alternate suggestions with more specifics about what you're actually ultimately trying to achieve.
Hope that helps!

Prevent Android App in background getting suspended

I wrote an App that will run process in a long time, possibly never ending until the user stop it.
But I afraid the App will get suspended when the mobile/tablet screen is sleep, or user switch to another app so that my app long running task is getting suspended.
How do I prevent that?
You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
You can use START_STICKY to make your Service running continuously.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
and see this :http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
and This is an example of background service:
http://marakana.com/forums/android/examples/60.html
What you want is implement a Service.
It will have that behavior that you are asking.
You should use a Service and return START_STICKY on the onStartCommand() so that the system will not terminate your app. Even if it is terminated, the service is automatically restarted.

want to write background location tracking application android

Hi Everyone I want to create location tracking application in android which runs in background even after user terminates application by left swipe from recent application. till now i have used intent service started from main activity but it gets killed when i terminate application.
Any other idea to implement this?
I have tried by registering location updates and doing work of service in onLocation changed event. but listener also gets unregister after application exists.
I don't need full code but i need approach to do this.
Have you tried to track in a Service? Without reference to the activity. You have the start the service from the activity for the first time.
Note: A service isn't killed by swiping from recent apps, rather it is killed by the OS when more ram is required. To restart it after its killed you have to return START_STICKY to onStartCommand i.e:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
Also, here you should register your LocationListener and perform whatever action you need.
And as always, remember to add permissions.

android - service stops when activity is destroyed

when I open the activity of my project I call the startService(Intent intent) method to start a new Service.
When the activity is destroyed the service shouldn't be killed (because I didn't use the bindService() method), but the fact is that when I close my activity the service is killed and after a second the system creates a new Service (I verified that, the system calls again the onCreate() method of my service). What do I have to do to keep only one service ? Thank you
To have a service running independently of your application's main process and to be sure that Android does not kill it while it's doing something, there are two things you should do/try.
Run your service in a separate process. You can achieve this by adding the following attribute to your service declaration in the manifest:
android:process=":somenamehere"
When your service is running and you do not want it to be killed by the OS, you have to use the startForeground(int id, Notification notification) method. When the service finishes whatever is doing and can be killed by the OS, call stopForeground(boolean removeNotification). "startForeground" requires a notification as argument because every foreground service must display a notification so the user realizes about it
I hope this helps you.
I mean I hold the home button and then kill my activity from the list of app open
That does not "close" an activity. That terminates your process. The user is welcome to terminate your process whenever the user wants, whether via this means or through third-party task manager apps. There is nothing you can do about this -- you cannot stop the user from terminating your process. Since your process will stop for other reasons as well (e.g., sheer old age), you have plenty of reasons to handle this case.
Edit: Please refer to CommonsWare's answer
Old answer: You should override public int onStartCommand(Intent intent, int flags, int startId) method and return START_STICKY value as the mode of your service.
this will keeps your service working when the activity is destroyed or even when you exit your app unless you call stopService(Intent) explicitly

Is it possible to run my service for indefinite time?

Can I run a background service Indefinitely ? Will android kill my service if i run it for indefinitely ? How Facebook android application keep running in background for a long time ?? please help me to know about it .
You can use for that these features:
1) Auto-restart service after reboot (Start intent after Reboot)
2) Sticky service mode (http://developer.android.com/reference/android/app/Service.html#START_STICKY)
These features both helps to leave your service started all time as possible.
Android will kill your service if it's running out of memory, but you can do a couple of things to recover from it.
The first thing you can try is to use foreground services, a foreground service is a high priority services that won't be killed unless is completely necessary (note that these services increase battery consumption). You can find an example here using compatibility with older devices, otherwise you only need to call startForeground inside your service.
Another thing you can do is to use some flags in your service to restart it when it gets killed by the OS. You can use 2 different flags (depending on which behaviour you want to reproduce).
START_STICKY will restart your service with an empty intent so everytime you have to recover the data you need to run your service.
START_REDELIVER_INTENT in this case your service will be restarted with the last intent information (it could be that you run your service several times with different information when you want different behaviour).
The flags can be used as follows:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Do your service work
return START_STICKY; //or return START_REDELIVER_INTENT;
}
Depending on what you need use one or another.
Hope it helps :)
There's no way to absolutely protect a Service from being killed.
If you return START_STICKY from onStartCommand(), then even if Service is killed, android will try its best to start it again, when resources are free.

Categories

Resources