Anywhere I've looked for this topic says (resuming): "call finish() on your activity and if you have any services running, call stopService() on them".
So that I did, and as it seemed to work, I stopped worrying. Today, debugging a part of my code, I needed to add a Log line into a non-ending thread's method which I want to be executed all the app's life, basically it's something like this:
final Thread buf_liberator = new Thread(
new Runnable() {
public void run() {
while (true) {
methodCall();
SystemClock.sleep(9000);
}
}
}
);
buf_liberator.setPriority(7);
buf_liberator.start();
In methodCall() I put the Log line, and for my surprise, after I closed my app pushing the Exit button which calls finish() and stops a service I've started, I still see the Log message every 9 seconds indefinitely in the LogCat.
So the question(s) is(are): This thread is not a service, why it keeps running? Am I doing something wrong? Is this an expected behavior? Is there a real method to destroy everything the app had in memory?
Thanks!
So the question(s) is(are): This thread is not a service, why it keeps running?
Because your process is still running. Even when you finish() an Activity or stop() a Service, your application process may keep running.
Am I doing something wrong?
Besides creating a never-ending thread? No.
Is this an expected behavior?
Yes. The Android system keeps process around as a caching mechanism to speed up resuming previously used apps. The system will eventually kill your process (and the running thread) as it deems necessary. Do not count on your thread not ending, because it will, eventually
Is there a real method to destroy everything the app had in memory?
There are ways, like System.exit(), but it's generally advised that you let the system work as intended.
Further Reading:
http://developer.android.com/guide/components/processes-and-threads.html
You don't need to worry about this. There is no such thing as "exit application" in Android. When application is launched, Android spawns a process where your application "lives". When your application starts an Android component (like an Activity or a Service), then Android knows your application is active, and it will try to keep it in memory then. If you close all activities and all services, your application's importance gets low. Since now, if Android needs more memory, it will kill the process hosting your application at any time.
In your case, you closed all components, but kept a thread running. It has continued to run in background because Android didn't need more memory and your app stayed "cached" for possible future use. If you had started a memory consuming game then your app would have been killed. So you cannot rely on the thread running outside of an active component (like a service) as it can be killed at any time.
If you really want to exit the app, you can try to call standard Java function System.exit(0). This is not necessarily needed, but you can use it if you want to.
Related
I have a long running background task that I would like to start when the app launches and shutdown when the application shuts down. I'm already quite aware of the activity life cycle and what gets called when an activity gets created and destroyed.
I'm coming from an iOS background, and over there we have some calls that are made during application startup and shutdown. Is there something similar in the android world? I've searched a lot and all I'm finding are answers relating to an activity, not the entire application.
(Android is relatively new to me, so I may just not know the correct terminology to search for.)
EDIT:
I'll try an be a bit more specific. I have a background task that needs to be continuously running while the user is using the application. It will be streaming data from a server continuously while the application is active. It does not need to run when the application is in the background. It doesn't seem to make sense to me to tie the startup / shutdown of this background process to any one single activity since it may not be the same one activity that starts up when the application becomes active.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses. If that is, in fact, the case, then all I really need to do is spin up the background task when the application first launches, i.e. when it is loaded into memory and becomes active for the first time that session.
It doesn't seem to make sense to me to tie the startup / shutdown of this background task to any one single activity since it may not be the same one activity that starts up when the application becomes active.
That's reasonable. It is somewhat difficult to implement, though.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses.
You have it exactly backwards. Android pays not one whit of attention to any threads that you fork yourself, directly or via thin wrappers like AsyncTask.
In addition to that point of confusion, you appear to be equating "user switching to another app" with "app shutdown". Those may be the same thing in single-tasking operating systems. They are not the same thing in Windows, OS X, Linux, Android, etc.
So, what you seem to be seeking is having a background thread running doing this streaming work while your UI is in the foreground, and then stop when your UI is in the background. The problem is that there really isn't a straightforward way of accomplishing that in Android.
One close approximation would be to create and register a custom Application class, where you override onTrimMemory(), and stop your background work when you get to TRIM_MEMORY_UI_HIDDEN, TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE, or TRIM_MEMORY_COMPLETE -- whichever of those that you encounter first. If, when one of those arrives, you determine that your streaming thread is still outstanding, shut it down.
In terms of startup, you could use onCreate() on that same Application singleton. The problem is that this will be called on any process creation, which may include scenarios in which you do not have UI (e.g., you are responding to some system broadcast, like ACTION_BOOT_COMPLETED), or possibly your process is going to parts of your UI that do not depend on the streaming. If you have none of those scenarios, then onCreate() in Application would be fine. Otherwise, kick off the streaming in onCreate() of whatever activities need it.
While normally we manage long-running threads with a Service, that is for cases where we explicitly want the thread to continue after our UI is in the background. Since you do not want that, you could skip the service.
It depends on what you want to do exactly. When you're just interested in the app starting for the first time you could #Override onCreate().
Or maybe you want to use onResume() as this will get called whenever a user brings the app to the foreground.
But this really depends on what exactly your background task is doing and what you want to do with it, to get an exact answer you need to provide more details.
Here is an overview for the actiity life cycle that should help you:
You can extend the default Application class and implement it's onCreate() method to detect when the app is launched. There is no corresponding method for when the app gets closed though.
Do not forget to specify it in the Manifest file.
In Android the application isn't shut down unless the system runs low on memory. You won't get a warning about that, it will just call your Service's onDestroy lifecycle method. If you want to do it when the Activity is visible on screen, use onStart and onStop. If you want to do it when the Activity is resident in memory, use onCreate and onDestroy.
I have some confusion with android service
As per the documentation
It will keep on running in the background on main thread . It doesn't run in a different thread.
My doubt is what is the meaning of keep on running in background . Will it execute the onStartCommand() again and again. I am really very confused with this line (Keep on running in background )
if it will not execute onStartCommand again and again then what is the benefit of Keep on running and if it executes onStartCommand again and again then it is using cpu more and more
Line which confused me is highlighted in the image please have a look
As already noted in a comment, for your particular purpose (monitoring a setting, here: volume), you can follow a non-polling approach which is described e.g. here: Is there a broadcast action for volume changes?
In general, on a modern (though not perfect) environment like Android, there's almost never a reason to actively poll something, because nobody could afford wasting so much resources, and also, you'll always risk to miss events, so you'd be tempted to poll more frequently -- this is a race which your implementation is always going to lose.
Once more, the following statements are plain wrong:
A Service runs on your app's main/UI thread. If you think this is the case then you need to read about the android:process attribute of the manifest's activity tag. Also. even if you do not let your service run in a separate process, the phrase a service runs on your app's main/UI thread suggests that your main/UI thread gets blocked by your service. Of course, hopefully nobody leaves iot art that; it's easy to just process the service's events on your app's main/UI thread and delegate the tasks to worker threads, which is what every sane implementation should do.
With START_STICKY, you can ensure that your service will always be running after it got started. Of course, this is naive and means that whoever claims this has not completely understood the meaning of this flag in conjunction with the description of the process lifecylce for Android Services. Quote: Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If you read the section, you will know that Android is going to kill the process with your running service at any time without notice if it needs memory for another task with higher priority and your service is not related to an app which the user currently looks at. In other words, if the system is low on memory and the user opens a spreadsheet which requires most of the system's memory, then the background internet radio media player and all fancy stuff is likely to get killed, period.
A Service runs on the thread of your app and after started it keeps running until it calls finish() or android needs memory.
But the running doesn't necessary means that it is processing something. onStartCommand() is called only when someone calls startService() on your service.
So the service instead of running always it's always in memory ready to be run when needed. The main use of service is to do some processing that keeps running even if you change activities, like a music player that keeps playing when you are changing activity looking for the next music to play.
Edit: On Documentation "A Service is not a separate process....A Service is not a thread. It is not a means itself to do work off of the main thread".
A Service is "A facility for the application to tell the system about something it wants to be doing in the background"
"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."
Service Documentation
I have an Android application that has a need to perform work in the background and on a separate thread. For my first proof-of-concept I subclassed the Application class and inside onCreate() I spawn a Thread that does the background work. This works just great. However, I just realized that in the past I've used a service for situations like this.
The question is, is there a reason to do work on a Thread spawned from a Service instead of a Thread spawned by Application.onCreate()? The Service is supposed to perform "background" work (it uses the UI thread unless a Thread is used, I know) that is independent of the Activity and can run while no Activity is visible. Using an Application-based thread seems to accomplish all this just as well. By not using a Service it actually removes complexity because the Activity just accesses the Application singleton. As far as I know I have no need to bind to the Service.
Will I get bit by lifecycle corner cases that using a Service would prevent? That's the only concern I have over this approach, but otherwise I'm not sold on the benefits of a Service.
The difference would be if you want the thread to run in the background only when the Activity is running or if you want it to continue to run when the user leaves.
Services are capable of running in the background even when the Activity is no longer available. They are intended to be used when your app should continue to do work without any user involvement in the near future. If you run the Thread in the Service, the thread will continue to run even when the user leaves the app. This can be beneficial sometimes as the user may want you to keep downloading a really large file but doesn't want the app to continue to run in the foreground. Then, a few hours (days, months, years) later the user can re-enter the app to read the file.
If, however, you're using a thread that needs to constantly update the UI based on results, it may be more beneficial to launch it within the Activity since it has no real purpose to run in a Service. It also may be easier in your program for your Thread to talk to the UI if it's in the Activity rather than the Service. (There may be some performance benefits as Android doesn't have to handle yet another Service on it's list, but that's purely speculation on my part. I have no proof of it.)
NOTE: Threads created in Activities will still continue to run even when the Activity quits. However, this is merely because the app is still in memory. The Activity and it's thread are on a higher priority to be deleted from memory than a Service thread when the Activity is no longer within view.
If your application is not either in the foreground, or visible, then it's more likely to be killed off by the system. If you run your code as a service, rather than a thread spawned by a background process, then your task will survive for longer. No guarantees, so you still need to manage the process lifecycle properly, but running as a service is likely to give more reliable results.
See http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
My situation:
I have created an Android service, which is started when the app is started. The service consists of a simple Thread that waits for 5 seconds, writes a log message and waits again.
After closing the application (using the back button), Android chooses to restart my service , because I am returning START_STICKY in OnStartCommand.
When debugging the application, I can actually use DDMS to kill the process. Android again chooses to restart the service. This is expected as per the manual.
I also installed a task manager, and used that to "kill" the instance. Funky thing, is that now my service is no longer restarted.
The funky thing is this: in either case, no destroy code of my classes is called. No InterruptedException is raised on my waiting threads. There seems to be no way for my application to know it's being destroyed.
My question:
How can I get around this, and respond to kill requests? I already noticed that the DVM lacks sun.misc.Signal and sun.misc.SignalHandler for proper signal handling (if that's even being used by task killers).
I kind of need to know wether my app is being destroyed, so I can properly close file handles, database connections and the likes.
Many thanks for any assistance.
How can I get around this, and respond to kill requests?
You don't. OTOH, this task killer behavior should have been eliminated in Android 2.2, so it eventually will not be a problem.
IIUC, there should only be one instance of a given Android service, it is a singleton.
However, my service gets instantiated multiple times, although I
do nothing for it.
When the service crashes (for example when I uninstall the app through adb), it
gets scheduled for restart ("Scheduling restart of crashed service.. "). I
understand this is an effect of the service being sticky.
After that, when my app starts, it calls startService() and bindService(), and
the service gets appropriately started and bound. But the service is then
reinstantiated and onCreate() is called repeatedly, as many times it was
scheduled for restart.
Each instance then wait for clients to bind and register, but onBind() is only
called in the "main" service instance. The additional instances wait a bit for
client to bind, and since that doesn't happen, they call stopSelf().
But stopSelf() has absolutely no effect in these "dead" instances, onDestroy()
is never called.
The "main" service instance does work as expected, and when it decides to call
stopSelf(), onDestroy() is indeed called.
Worse, all these dead instances accumulate, they never gets destroyed.
Therefore, their only possible end is a crash (which happen every time I
launch/install through adb), and thus scheduled restart.
So that in the end I get many of these dead instances, which are restarted
progressively once by minute approximately.
Does anyone know what's going on?
I got similar behavior if I use eclipse to restart an app with a remote service. According to logcat, system consider the killed service had a crash and tried to restart the service. At the same time, the service has been restarted with the restarted app. For some unknown reason, Android system does not realize there is already a running service, and tries to start a new one.
It happens several times on Optimus one, Galaxy tab, and EVO 3D. It is fine with Nexus one.
Because I haven't seen your code, this is just a guess: Maybe you have a memory leak that prevents the service from destroying properly. That's the only reason I could think of to get multiple instances of service. For example, if you service is holding on to some object that also have a reference to your service. It happens a lot with inner classes.
Check out this video from Google I/O to see if this problem applies to your services and how to find it: http://www.youtube.com/watch?v=_CruQY55HOk&feature=player_embedded
if you use the section to be excecuted in onstart() . if ur starting the service by onclick button or like clicking on icon multiple time means ,what it will do is if service is already running means ,it will go to onstart(),so the method is excecuting again and again its not that service is starting multiple times .... ur method is running for multiple time ,This i told accornding to my guess may be exact code will be Explaind properlly
if your app exit on crash or kill the process it belongs to like System.exit(), it will start after your app exit or start if your service is running in the same process with Application.
Because you kill the process, and Android detect your service should not stop, so Android restart it for you after your app exit. And why service start again after app restart, I think it is Android's bug, it reallocate a new process to your app instead of using the process allocate to your service.
So, how to solve this problem?
just set the attribute android:process=":background"(whatever you want here, starts with :) to your service node in AndroidManifest.xml. hope it helps you.