Is it possible to identify who destroyed the service ?
I have a service that is running in the background and when the user clicks a button i call
stopService(myService):
and
onDestroy()
is then called . Sometimes the service is destroyed by the operating system for one reason or another . is it possible to find out if the user stopped it or was it the system ?
I have a service that read accelerometer data and based on it an action is taking .
the service i running fine but some times the system terminates this service and when that happens i want to service to restart self using AlarmManager after a set seconds of time.
I want to check in onDestroy() if the user is the one who stopped the service thats by callking stopService() or the system did . if the user did then there is no need to restart the service but if it was the system then restart it
You haven't provided enough information to be sure but you're most likely looking at the background limitations of Android Oreo. To increase battery life all background services will be stopped by the system a few minutes after the app moves to the background.
More information about the background limitations can be found here.
If your Android version is lower than Oreo or your app is still in the foreground you'll need to provide more information about the circumstances.
#HemantParmar gave a good link to read, it is simple to check if user destroyed the service or system itself, whenever you call stopService() use a boolean flag.
//runningService.stopit();
// OR
stopService(RunningService); // user called
boolean iStopped = true;
public void stopit(){
//stopSelf();
}
public void onDestroy(){
super.onDestroy();
if(iStopped){
// user did it
}else{
// system did it
}
iStopped = false; // whoever did it , reset it
}
stopService() & stopSelf() are called only when you want to explicitly destroy service which in turn call onDestroy().
And onDestroy() will also be called when you service finishes itself.
Please refer for more details:
Android: stopService() doesn't call onDestroy()!
https://developer.android.com/guide/components/services
Related
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!
I have an Android app that connects to surrounding devices currently running the same app, even if in background.
To do this, I use WiF-Direct to advertise the fact that I am currently running said application.
Therefore I need to stop advertising this as soon as the app is killed.
onDestroy() cannot be used since it is not guaranteed to be called.
onStop() and onPause() cannot be used since the app is still running.
How can I achieve this?
Currently the service is still being advertised even when the application is closed/killed.
You should be able to do this with a Service.
Start a service when your app was started.
Override the onTaskRemoved method
#Override
public void onTaskRemoved(Intent rootIntent)
{
}
In this method do what you have to do.
More detailed answer can be found here: How to know when my app has been killed? (2 answer)
The best implementation might be to have another service running that queries the your app is in foreground(i.e. running)
You can run the query to check periodically say every 60 sec. Then if the app isn't running. You can stop the WiFi Direct service and subsequently stop self.
I created background service on android tab using startService() method inside the Activity.
Then I create a Thread on onStart() method. I read from the android developer site that service are independent of the activity, but when I destroy the Activity android system kills the service too. I want the service to continue until I do not stop it myself.
I am aware that it can be done using AlarmManger but it consumes battery. There is no need of push notification, but the service needs to run in the background. Any suggestions on how to solve this?
Use this in your service class and call it by using button
#Override
public void onDestroy() {
Log.e("serive destroyed", "service distroyed");
super.onDestroy();
}
check this link for AsyncTask won't stop even when the activity has destroyed & in that check the Answer Posted By Snicolas.And take Reference of other Answers. Hope this helps.
It should not generally happens when activity destroys service also destroys.
Services are components that run in the background, without a user interface.
More important, Android services can have life cycles separate from activities. When an activity pauses, stops, or gets destroyed, there may be some processing that you want to continue. Services are good for that too.
I am developing android application which has background running Service.
When I swap out app from the "Recent app List", it will cause the application to shutdown and stop the service. (The following method has the code for the same.)
#Override
public void onTaskRemoved(Intent rootIntent)
{
//code to be executed
//Stop service
super.onTaskRemoved(rootIntent);
}
Service start up code is in Application class(onCreate()), it will never be executed if app gets resume.
Positive Scenario
1) If I relaunch app after successful execution of service, new instance of app will be
created and service will also start.
Negative Scenario
1) Because there is some code in the above method which is responsible to stop the thread and the service, it causes the app to take some time to stop the service (after swapping from the recent apps).
During this time if I relaunch the application, the application resumes instead off getting recreated.
Now, the service which was running, will stop.
So,in this type situation I have application but without background service.
How can I handle this situation?
1) Application shouldn't be re-launch until service's task is completed.
2) Start service from launcher activity.
Thanks in advance.
in onStartCommand() of Service class , You have to set return as "START_STICKY" that ensure restart service which is terminated by android platform(if app breaks).
You can check the status of the service in OnResume and restart from there using Intent
#Override
protected void onResume()
{
/* This will be called when starting the UI and resume from background
* If the service is not running, then start the service and bind to the service.
* If the service is already running, then just bind with the service. The status
* of the service is determined by the #DetermineServiceStatus function.
*/
}
You have almost no control over service' s lifetime. Background services are prone to be killed by Android, whenever system needs more resources.
The best way to design a background service is return a START_STICKY from your onStartCommand() (which you already did) to ensure that when enough resources become available, your service automatically be restarted, and the job that you perform within the background service should be implemented so that even if it is interrupted, it should succesfully continue its task when restarted by Android OS.
My android application starts a service in the onCreate() callback of a class that extends Application. The service performs some background tasks that are relevant to the user only while the application is running. For that reason I would like to close the service when the application's last activity is closed. I've tried to perform closing the service in the callback onTerminate() , but it never gets called . So what would be the best place where a service should be closed ?
Thanks !
An Android service, once started, will continue running until the Context.stopService() or stopSelf() is called.
There are various hooks you can use to stop the service using Context.stopService (the service itself, or an onDestroy()/onPause callback in one of the activities, or a button click).
It's true that Android does some resource management itself, but it can take a long time before Android decides to terminate your services. And a service that's running but not doing anything just consumes resources on the phone that other apps might need.
In your case, the onPause method of your last activity would be a good that will get called, and as such is the correct place to stop the service.
The onPause() callback will be made when your activity is paused for any reason, and you know that when this happens your app will not be visible again until onResume() is called. If your service has a reason to run in the use case that your activity might be started again soon, you should add an entry to your service that onPause() calls, to set a delayed service termination. In onResume() you can cancel that delayed termination through another entry.