Android process lifecycle & services - android

I have been reading about process life-cycles after I noticed that android unexpectedly terminated my app. The app is normally running also in background but now it was terminated. The app listens gps location updates, battery state broadcasts, receives sms broadcasts, runs Bluetooth and tcp server etc. So it has quite a lot of jobs to do and until now it has succeeded pretty well.
What I found out was that android probably closed the process due to low RAM. My app was still in the 'app swap' list but when I selected it I noticed that it was actually restarted which explained the fact that I was not able to connect it earlier using tcp. Do you agree my conclusion or is there any other reason than low RAM that could cause this?
After reading a bit more I understood I should have implemented almost the whole application as a foreground service because those will be killed only after there are no normal activities to kill. However I'm not that comfortable in doing such a bit changes to the application at this point. BUT, then I found this:
http://developer.android.com/guide/components/processes-and-threads.html
There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last):
Foreground process
A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:
-It hosts an Activity that the user is interacting with (the Activity's onResume() method has been called).
-It hosts a Service that's bound to the activity that the user is interacting with.
-It hosts a Service that's running "in the foreground"—the service has called startForeground().
-It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
-It hosts a BroadcastReceiver that's executing its onReceive() method.
Please correct if I got the bolded condition wrong. Doesn't it mean that I could just make my app to host a dummy foreground service after which the process running my app and the dummy service would be considered as foreground process which again would mean that it would be very unlike that Android killed my app?? This way I wouldn't have to go through all the functions my app has and to figure out how to get them work as a service.
Thanks!

Related

How to keep android process alive

How does the apps like Swiftkey, Locker Master manages to keep process alive even after it has been removed from back stack?
They also don't use sticky notification.
Update:-
I need to keep my process alive. But in my case service is active but process gets killed.
They all have one or more unbound background service.
To kill those services you can go into Settings -> Apps -> Running.
However the services may be restarted at any time by other apps or system by sending a system wide message (intent). In most cases it is restarted by
Time events
Boot complete
Other apps
Other intents
In the Swiftkey case, it will be started by Android OS when it needs to show a keyboard.
EDIT: you can specify that a service runs in a remote process by adding this to the service definition in AndroidManifest
android:process="process_name_here"
However there is no such thing as a service that cannot be killed and can run forever. Android OS may start killing your service if it is running low on resources or the service is running for a long period of time. To overcome this, you can make a forground running service, but it needs to show a notification. It can also be killed by task managers, like you mentioned. You should instead start focusing on how to save it's state so you are able to restart it later.

Android service that doesn't close with application

I have been searching the net for hours. I am trying to make an application that has a UI interface and a service running in the background for SIP phone communication, kind of like Skype.
The UI starts and stops the service based on UI events, and the service stays logged in with a internet server in the background. I have found many articles talking about running the service on a separate thread(done), using startService as opposed to binding the service(done) but whenever I use the task manager to kill the application as a user might, I get an error popup saying my application has crashed and the service no longer runs.
How do programs like Skype, Facebook, or email clients do this?
Do I have to run these as separate applications using implicit intents?
Is there some settings I have to set in the manifest file other than declaring the service and it's name?
Better yet, is there a link to some page or source example using this kind of service?
EDIT: Sorry, I guess I wasn't clear. The service is stopping, and I don't want it to. I am trying to keep the service running in the background even after a user kills the application with the application manager.
One of the more confusing things with Service is that it is not run in a separate thread by default. Calling startService() as opposed to bindService() makes no difference in this regard. However, the binder mechanism will cause the Service exposed methods to be called in arbitrary thread context. In both cases, your Service is part of your application's process. If you kill it via the task manager or it crashes then the Service dies as well.
When you kill the app via the task manager and it pops up the message about the app dying, you have something misbehaving. Check logcat and it will point you at exactly where the crash happened.
If you need to have your Service running regardless of the UI, then don't stop the Service when your UI exits. You will still call startService() when your UI starts to re-connect (and possibly re-start it), but don't stop it unless you really want it stopped. Starts do not "stack". If something calls start 5x it doesn't take 5 stops to terminate the Service, only 1.

Android Background Process

I am wondering that why there is still a process running even I had already left(pressing back button) the Flickr and the Messenger apps in the picture above?
Recently I wrote an app that contains a service, I've found that if there is still a process running, the service will less likely be killed by the system.
So how does the apps above keep processes running in background?
They uses background service that will stay alive even if you quit the app.. as the documentation said
The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it
As long the app is not ended service will stay alive unless there is no memory left.
When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:
If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.
If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.
If there are clients bound to the service, then the service's hosting process is never less important than the most important client. That is, if one of its clients is visible to the user, then the service itself is considered to be visible.
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
you can learn more about Service here
The back button doesn't end the app, its like minimizing them in Windows. TO end them they need to be call finish. Androiud's design (which I think is a stupid, insecure idea, but its how it works) is that apps will not exit unless they exit themselves with finish or you run low on memory and the OS kills them.

Foreground processes in Android

With respect to Process lifecycle, Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.
One of the classification is :
Foreground Process : A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:
1. It hosts an Activity that the user is interacting with.(the Activity's onResume() method has been called).
2. It hosts a Service that's bound to the activity that the user is interacting with.
3. It hosts a Service that's running "in the foreground" —the service has called startForeground().
4. It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
5. It hosts a BroadcastReceiver that's executing its onReceive() method.
What can be real life examples of scenarios given above I am asking this because it will help me and others as well in differentiating between this situations.
1)THe app that is currently on top of the stack (the one the user is using)
2)An app with an Activity that has called bindService on any service. The idea is that if it killed that service, it might lose data. An example of this would be a facebook app, which has a background service to fetch data every so often. If the user has it open, it would qualify
3)This is a service that has declared that its feeds data to a UI. An example of this would be a facebook app where the user didn't have an activity with it open
4)This is a service that's just starting or just finishing. This would be pure luck to have happen, but its basically saying it will try to let it start up or finish cleanly before killing it
5)This is any app that's currently responding to an event. An example would be an SMS app that was just notified of an incoming SMS and needs to deal with it. It will be allowed to run until its done, because doing otherwise may lose data.

BroadcastReceivers and Memory Usage

I've not had the time to play with receivers, and also I'm unfamiliar with anything above 2.3.x, so I was totally puzzled when I read this question:
Can BroadcastReceiver registered in AndroidManifest receive intents when application process is killed?
Its author is able to see the BroadcastReceiver application in the task manager list, and when the app is killed, the broadcast receiver no longer is called. This is due to a new mechanism introduced in 3.1:
http://developer.android.com/sdk/android-3.1.html#launchcontrols
In that link, the stopped state for an Application is mentioned. Application lifecycle isn't explained anywhere in the docs, AFAIK, so I guess an App can be in one of these 3 states:
Stopped (not in RAM)
Started (in RAM, not running)
Running (in RAM)
For the user to be able to see the app in the Task Manager, it should be in either started or running state (I'm guessing here, because I don't know if there are more states). And seems that the app was showing in the list for a significant amount of time. If a receiver app is started or running, it must have a linux hosting process with its own Dalvik VM instance. This is in conflict with my previous beliefs on how receivers should work:
When a receiver isn't running, there's no performance penalty to the system.
Once a receiver needs to be notified, a new foreground process is spawned (if not already running), a new Receiver is instantiated, and the onReceive method is called.
After a max processing time of 10 secs, onReceive returns, and provided there are no additional Services or Activities, the hosting process is very likely being killed, thus releasing resources.
So, my questions:
If the app is shown in the task manager (hence there's a process), but hasn't been notified yet, why would the OS spawn a process for a receiver that hasn't even been notified (and might not be notified at all). If the app has been notified but the process hasn't been killed yet, (and so it is listed in the task manager), why doesn't the OS kill it shortly after it completes? Here I'm assuming the task manager only shows an application if it has a process allocated, but this raises the following question:
What are the chances of having a receiver process listed in the task manager? Does the task manager show the receiver app even if it is stopped? If so, is this the new behaviour for 3.1+ so that the user can notice it exists and force-close it? If not, the application should only be listed there if it is in the middle of a call to onReceive or after it returns and is eligible to be killed, which according to the docs, should be a short interval.
Thanks in advance.
so I guess an App can be in one of these 3 states: Stopped (not in RAM), Started (in RAM, not running), Running (in RAM)
Not exactly, at least as how I would phrase it, though that might be a terminology and/or language issue.
A process is either running or not running. It cannot be "in RAM" and "not running".
Independently of this concept, an application can have its manifest-registered BroadcastReceivers be disabled or enabled, as of Android 3.1. The docs refer to the disabled state as "stopped", which is a very unfortunate choice of terms on Google's part, one that I have complained about on several occasions. When you see references to this state, ignore any other definitions of the term "stopped". In fact, you might want to make up some other term for this state, such as "snicklefritzed".
Your app is snicklefritzed immediately after installation. Your app is moved into a "normal" state once something explicitly runs one of your components (e.g., user manually launches an activity from the home screen). Your app is moved back to be snicklefritzed when the user force-stops your app from Settings. The information about whether an app is normal or snicklefritzed is held in some OS-managed file and (AFAIK) is cached in an OS process.
Hence, an application is either:
Not running (no process) and snicklefritzed
Not running (no process) and not snicklefritzed
Running (has a process) and not snicklefritzed
(it is not possible to be running and snicklefritzed, because the act of running something would have moved you out of the snicklefritzed state, and a force-stop would terminate your process)
When a receiver isn't running, there's no performance penalty to the system.
Correct.
Once a receiver needs to be notified, a new foreground process is spawned (if not already running), a new Receiver is instantiated, and the onReceive method is called.
Correct.
After a max processing time of 10 secs, onReceive returns, and provided there are no additional Services or Activities, the hosting process is very likely being killed, thus releasing resources.
I would phrase it as "the hosting process is eligible to be killed and will be relatively high in the priority queue to be killed as the OS needs RAM for other processes".
Why would the OS spawn a process for a receiver that hasn't even been notified (and might not be notified at all).
It doesn't. A snicklefritzed app's manifest-registered BroadcastReceivers are ignored.
What are the chances of having a receiver process listed in the task manager?
100% while the process is running. 0% when the process is not running.
Is this the new behaviour for 3.1+ so that the user can notice it exists and force-close it?
I have no idea what you are referring to when you say "this" and "it".
Or is it the normal behaviour when the system has enough memory available, even for 2.x OSes?
I still have no idea what you are referring to when you say "it".

Categories

Resources