calling onDestroy in android shutdown - android

If I have a service running in my Android phone and I shutdown, will the service call onDestroy? I want the service to perform a task just before the phone shuts down. Although the Google Droid guide says not to put such code in onDestroy, I do not know what else can be done.

If startService() is called to create your Service you should call stopService(), then onDestroy() will be called. If you use bindService() with BIND_AUTO_CREATE flag, than unbindService() caused onDestroy() automatically. What code they say shouldn't be put there? If it uses this Service of cause onDestroy() is not a good idea, if it's something like notification it's ok to put it there.

Related

Is it necessary to check already running service list before starting or stoping a service?

while going through a code I found that before starting or stopping a service
a check was placed to confirm whether the service is already running or already stopped.
This was done using Activity Manager which gives information
about already running services in the System.
I want to know is this check necessary ?
what would happen if I call startService() for an already running service ?
What would happen if I call stopService() for an already stopped service ?
As it is mentioned in the Android docs
Note that multiple calls to Context.startService() do not nest (though
they do result in multiple corresponding calls to onStartCommand()),
so no matter how many times it is started a service will be stopped
once Context.stopService() or stopSelf() is called; however, services
can use their stopSelf(int) method to ensure the service is not
stopped until started intents have been processed.
So on your question
what would happen if I call startService() for an already running service ?
The onStartCommand() is called again and again but service once started cannot be started again or nested
What would happen if I call stopService() for an already stopped
service ?
When you call it first the onDestroy() method is called and later calls are ignored as service doesnt exist any more
If the service running, it does not create another instance, but onStartCommand() is still called on the existing instance.
You may look into Service Life cycle for more details.
Note that multiple calls to Context.startService() do not nest (though
they do result in multiple corresponding calls to onStartCommand()),
so no matter how many times it is started a service will be stopped
once Context.stopService() or stopSelf() is called; however, services
can use their stopSelf(int) method to ensure the service is not
stopped until started intents have been processed.
As for stopService, it wont affect anything even if the service in question is not running in my knowledge.
A service will only run once, no matter how many times you call startService().
Calling stopService() will make no effect on an already stopped service.Its like calling onDestroy() on a already destroyed Activity.

Android - Service - onDestroy() method not called when using Force Stop

When I stop a service using the stop button under the Running Services tab, the method onDestroy() is called.
But when I force stop the application, onDestroy() is never called.
Any explainations about this?
or maybe a solution to fire onDestroy() when force-stopped?
When your force stop an app, exactly that happens - It is Force Stopped. No warning, no callbacks, just stopped. The entire process is killed, and none of the running components (Activities, Services etc) are given any warning.
There is absolutely no guarantee that onDestroy() will be called. Move any application critical code into onPause(), which is called under most circumstances.
From the documentation:
Once the activity is created, onPause() is the last method that's guaranteed to be called before the process can be killed... onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage.
To reiterate this point, Force Stop isn't intended to be graceful and exit the app in a caring manner. If you have critical code that must be run each time app finishes you need to run it in onPause().
When the application gets force stop, Process.killProcess() is called but not onDestroy() function. Go through this link. You will get some idea.
Android force Stop callback to application?
I am assuming you have code that you want to execute in onDestroy() referring to your line:
"or maybe a solution to fire onDestroy() when force-stopped?"
The Service method public void onTaskRemoved(Intent rootIntent) is what you are looking for, it will be called when the app is force-stopped.
I know it's an old question, but I was having the same issue and in my case I was using a binding service, so even after called stopSelf() Android does not call onDestroy() method, in order to force it I need to call unbindService() first

StopSelf does not stop my service

Googling around, I have seen this problem posted many times, some of the posts on this forum over that last few years. I have never seen anyone get a straight answer.
I have a foreground service that tries to stop itself after running for 2 hours by doing a this.StopSelf(). I've tried it when it's bound and when it's unbound. On the AVD and on a device.
It simply does not work. Is this a bug in Android? (running 2.3.3).
How can a service stop itself?
If you use a foreground service, you should call:
stopForeground(true);
Just like you start it with startForeground.
stopSelf is meant to be used for normal services. a foreground service is special... :)
By the way, in case your app should work on older devices, you should check the compatibility code offered here.
The only way I have found to stop a service with certainty is to use:
android.os.Process.killProcess(android.os.Process.myPid());
This behavior can be caused by using worker threads that have not finished when the stopSelf is called. If you are using worker threads, be careful how you employ this - you may leak memory if you don't clean up before executing the line.
I met a similar problem.Through my search found that: In other activity's onCreate method I bind the service,but not unbind it onDestory method.After fix that,when I call stopSelf then the service's onDestory method is call. I hope it can help you.
At same time,I find base from Android gover document.
A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().
I had this problem and searching I found this thread. My app's problem is that when service calls stopSelf(), the foreground activity that binds the service is still running. Thne stopSelf is called but the service is not destroyed as the foreground activity is still bound. When I leave the activity by pressing back or going to home screen, then the service is destroyed. In short, stopSelf won't work when a foreground activity is bound.
I encounter this issue of selfStop() that not working too.
The main idea to understand is that the Service WILL NOT stop,
if a running loop is still running (while(mDoWhile) for example).
Or any other issue that need to be destroyed / unregistered first.
So to make the stopSelf() or stopService(intent) works,
implement onDestroy() within your service:
#Override
public void onDestroy()
{
// Unregistered or disconnect what you need to
// For example: mGoogleApiClient.disconnect();
// Or break the while loop condition
// mDoWhile = false;
super.onDestroy();
}
if you both called startService and bindService.you should unbindService frist,otherwish the stopSelf will not work.
I was facing same problem too.
As we all know that Service runs on App's UI Thread. So, until you've Thread that is running in background in your service and you are calling stopSelf() then it won't work. For that you have to stop that Thread first and then execute stopSelf().
After stoping all background Thread from your Service stopSelf() method will definitely work.
The only way i had to kill the foreground service was to set stopwithtask=true in the manifest
<service
android:name="my.package.MyForegroundService"
android:foregroundServiceType="location"
android:stopWithTask="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
</service>
In my case of foreground service, it was necessary to remove location updates, unregister sensors, etc.
Add the following code to OnStartCommand when you want to kill the service:
private void selfTerminate() {
stopForeground(true);
unregisterBarometer();
if (locCallBack != null) {
getFusedLocationProviderClient(this).removeLocationUpdates(locCallBack);
}
m_tripState.currentActivity.clock.stopClock();
stopSelf();
}
stopSelf might not destroy the service if the conditions are not favorable, but you can stopService with the application context. But make sure the service doesn't restart before calling stopService inside service.
stopService(applicationContext, MyService::class.java)

If android restarts a Service is onCreate called again?

From my little android knowledge I understand that android OS can kill my service under extreme memory conditions.
I have created a service that returns START_STICKY. The service is meant to run in background.
If android is about to kill my service, will it call onDestroy ?
And when it restarts it would it call onCreate ?
See here, the dev guide. http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
onCreate() is only called when the process starts, which can either be the first time the service is running, or if it was killed on restarted, essentially this is called whenever it starts.
onStartCommand() is called whenever a client calls startService().
When a service is destroyed / completely stopped, Android is supposed to call onDestroy() on that service. I think it's possible for that to not happen (e.g. process is killed not through Android system). In the case of a bound service, this is when there are not more active client binders.
Edit: onCreate() Service starts; onStartCommand()someone uses service; onDestroy()Service is killed / stopped.
If someone calls Context.startService() then the system will retrieve
the service (creating it and calling its onCreate() method if needed)
and then call its onStartCommand(Intent, int, int) method with the
arguments supplied by the client
...
A service can be both started and have connections bound to it. In
such a case, the system will keep the service running as long as
either it is started or there are one or more connections to it with
the Context.BIND_AUTO_CREATE flag. Once neither of these situations
hold, the service's onDestroy() method is called and the service is
effectively terminated. All cleanup (stopping threads, unregistering
receivers) should be complete upon returning from onDestroy().
http://developer.android.com/reference/android/app/Service.html
EDIT: Quick answer. Yes to both questions

Service.onDestroy() is called directly after creation, anyway the Service does its work

I built a Service and it didn't work as expected, so I debugged it. During debugging, I saw that the service's onDestroy() method is called directly after returning from onCreate(). When I comment out the cleanup that happens in onDestroy(), the service does its work, but this should not be my solution. So my question is, why is onDestroy() called so early and why is the service running anyway? Or how can I prevent onDestroy() from being called at the wrong time?
For your information: I've subclassed IntentService.
Thanks for any help.
Binabik
If you are subclassing IntentService you should be using onHandleIntent(Intent intent) for the lifecycle of your service. Your service might be moving to onDestroy quickly becuase you do not have code inside of onHandleIntent. Although without your code I cannot say for sure.
Also it might aways move to onDestroy quickly because IntentService is auto threaded for you and might just launch the worker thread which calls onHandleIntent and move to onDestroy.

Categories

Resources