Foreground processes in Android - 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.

Related

How is a running IntentService managed after the app process is killed

Just trying to clarify my understanding of how an IntentService is managed by the OS once terminating states have been reached. By terminating, I mean when the current activity is destroyed or the app process is killed, as per the following documentation:
https://developer.android.com/guide/components/activities/activity-lifecycle
Given the comment
Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask
at https://developer.android.com/training/run-background-service/create-service;
I feel as if:
1) A started IntentService is unaffected by the activity lifecycle. Is this correct?
2) If (1) is true, will it continue to run indefinitely even after a terminating state is reached, up to some point that it either stops itself or the OS decides to stop it?
In my particular situation, I'm using an IntentService during app startup to query APIs, grab content, and then add a new (landing) Page to the Xamarin.Forms navigation stack (this would be equivalent to starting a new activity).
This leads me to my next question...
3) What happens if the app is already in a terminated state when it comes time to the IntentService creating a new Activity? Surely the Activity can't be added to the navigation stack as it no longer exists once the app is terminated?
Yes, a started IntentService is unaffected by the Activity Lifecycle. Actually, all Services outside of bound Services are unaffected by the Activity Lifecycle.
An IntentService will continue until it reaches completion of it's work, the application is destroyed, or if the System decides to kill the Service due to the changes in the Android 8.0 background Service rules.
Your use of terminated state is too broad... If the Application is already terminated, then nothing will happen because the IntentService would have been terminated already too. If it's the Activity that launched the IntentService that was terminated, then nothing happens, since by default, an IntentService has nothing to do with Activities, even if it's the one that started it.
For the last question, it really depends on how you choose to communicate the result of IntentService to an Activity.
If you're using a BroadcastReceiver, then nothing will happen because an IntentService will fire the broadcast without any problems, but the Activity won't be able to receive the results since it's terminated.
But if you're simply creating a new Activity, then you can simply use startActivity() with the result data added to the Intent. Though, I doubt the user will be happy to see an Activity suddenly open on the screen when they're no longer in your app. Starting a new Activity has nothing to do with a previous Activity, since any instance of a Context can start an Activity.
Honestly, based on your question, it sounds like you're very concerned with an IntentService and it's connection with the Activity that started it. If that's the case, you really shouldn't be using an IntentService, since that's not really it's purpose. It's not meant to have a connection with an Activity. It's simply meant to do work and finish.
Instead, a bound Service would be a better option since it has a direct connection with the Activity that started it.

Android process lifecycle & services

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!

new to android - understanding the use of the service

I have been going through this very short tutorialand I am confused as to what is the function of the service. I am also confused as to what is the function of the broadcast receiver.
I tried to do some research and here is what i understand:
- services run in the background, but... i don't understand why we need something
to run in the background to make the phone wake up at a certain time.
I "think" the broadcast receiver acts as some kind of catcher's mit, in that
when the pending intent is launched at a specific time, it catches it then
launches the service... how close am I to the truth ?
As i think that services are used for long running tasks and especially in those cases that run when your main activity is not running.
For this functionality we can use threads this make us to say that a thread is created inside our activity and it can't be active outside of the our main activity,
that is the drawback that's why we have services .
Document URL
Services can be used to run long running tasks independent of your screen flow. For example, consider your application require to communicate with a server via socket throughout its running duration, you can start a service to handle this. Imagine that against starting the socket and making connection at the start of every activity, and clean up when that activity stops.
Services by default run in the main thread. But you can start separate threads in a service context, just like you do in an Activity. If your background task can overlap across multiple activities, then it is better to start it in a Service context because every Thread/AsyncTask created retains the context that it is running. In that case your Activity will be retained even if user navigates to another activity because a thread started from that Activity is already running. If Activity is retained, it might prevent all its views, images getting garbage collected.
What Services can't do is to directly alter UI components. For that it needs to communicate with the currently running Activity context. In short, if your non UI task does overlap the life time of a particular Activity, it is better to shift that task to a Service.
What is the function of the service ?
A service is a component which runs in the background without direct interaction with the user.
As the service has no user interface, it is not bound to the lifecycle of an activity.
Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.
TO READ: Service
What is the function of the broadcast receiver ?
Broadcast receivers are the second kind of component. Like services, they only exist in the background and don't interact with you directly. But unlike services, they can't stay running or perform long tasks: they exist to respond to events. And unlike activities and services, more than one broadcast receiver can be started in one go.
Each broadcast receiver can react straight away, for example by creating a notification, or it can start a service or an activity to take further action. As soon as the broadcast receiver has handled the event, it is stopped and will not run again until another similar event is broadcast.
TO READ: BroadcastReceiver
I don't understand why we need something to run in the background to
make the phone wake up at a certain time ?
We don't want that the application should necessarily be in the foreground to wake the phone up.
Moreover we want notifications in the background.
We started the service. Now even if we close the application, you can get the phone wake up notification. This is so useful.
Services are great to interact with a user through notifications (a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information). Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.
To accommodate for such a requirement, android has introduced the "Service" component.
It runs in the background until it stops itself. This means that a service could be keeping your phone awake (using a wake lock), running down the battery, or using lots of network data, without anything showing on the screen.
I "think" the broadcast receiver acts as some kind of catcher's mit,
in that when the pending intent is launched at a specific time, it
catches it then launches the service... how close am I to the truth ?
Correct, they are meant to respond to an intent (usually one sent by a service or a system event), do something, and be done. When an intent is broadcast via sendBroadcast, it will be sent to all receivers that have matching intent filters.
Service - is a component of android, which runs in the background with out any UI. By default service will run in Main thread only.
Thread - is not android component, but still one can use thread to do some background task. Using thread in place of service is discouraged

Android application lifecycle when bound to a remote service

I have an android application that binds itself to a remote service once the application starts. The remote service provides an abstraction to a bluetooth video camera so we can send commands and receive events from it easily. The binding happens from the Application itself as opposed to an Activity. It is important to me that as long as the camera connection to bluetooth is active that my application stay running so I can receive events from the remote service. The main reason is that I need to know if it's recording or not and if so I need to periodically send it GPS coordinates.
Will my application have a better chance of not being killed if I use a service within my own application to manage that? Or is my application safe from being killed since it is still bound to the remote service? Of course, I understand that the android system will kill my app if memory requirements require it to but will it ever kill my app just because it's been sitting for awhile not doing much?
The application's process should only be removed if memory is low, but you will raise the perceived importance of your process if you use a service rather than an empty process or a background activity. You can also use startForeground() to make it less likely that Android will stop your service.
From http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle:
Process Lifecycle
The Android system attempts to keep application process around for as
long as possible, but eventually will need to remove old processes
when memory runs low. As described in Activity Lifecycle, the decision
about which process to remove is intimately tied to the state of the
user's interaction with it. In general, there are four states a
process can be in based on the activities running in it, listed here
in order of importance. The system will kill less important processes
(the last ones) before it resorts to killing more important processes
(the first ones).
The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most
important. Its process will only be killed as a last resort, if it
uses more memory than is available on the device. Generally at this
point the device has reached a memory paging state, so this is
required in order to keep the user interface responsive.
A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground
dialog) is considered extremely important and will not be killed
unless that is required to keep the foreground activity running.
A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may
safely kill its process to reclaim memory for other foreground or
visible processes. If its process needs to be killed, when the user
navigates back to the activity (making it visible on the screen
again), its onCreate(Bundle) method will be called with the
savedInstanceState it had previously supplied in
onSaveInstanceState(Bundle) so that it can restart itself in the same
state as the user last left it.
An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes).
These are killed very quickly by the system as memory becomes low. For
this reason, any background operation you do outside of an activity
must be executed in the context of an activity BroadcastReceiver or
Service to ensure that the system knows it needs to keep your process
around.
Sometimes an Activity may need to do a long-running operation that
exists independently of the activity lifecycle itself. An example may
be a camera application that allows you to upload a picture to a web
site. The upload may take a long time, and the application should
allow the user to leave the application will it is executing. To
accomplish this, your Activity should start a Service in which the
upload takes place. This allows the system to properly prioritize your
process (considering it to be more important than other non-visible
applications) for the duration of the upload, independent of whether
the original activity is paused, stopped, or finished.

Stop android app from closing

I'm using the BroadcastReceiver to receive SMS messages with my app, and then edit a database based on what the message says. The app works fine when it's open, but If I leave it on for a long period of time and it automatically closes the app will force close when it receives a message (I think the BroadcastReciever is still working, but the rest of the app has closed). IS there any way to keep the app from closing, or resuming it when it receives a text message?
Thanks
If you want the receiver to be persistent you should consider using a Service instead of a standard Activity for your application. BroadcastReceivers that exist in a standard activity are considered to be a foreground service only when processing onReceive as soon as the execution returns the Activity resumes its normal process priority and can be terminated by the system as needed.
From: BroadcastReceiver
Process Lifecycle
A process that is currently executing a BroadcastReceiver (that is, currently running the code in its onReceive(Context, Intent) method) is considered to be a foreground process and will be kept running by the system except under cases of extreme memory pressure.
Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.
This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.
For more information on creating a service:
Developer Guides
For a detailed discussion about how to create services, read the Services developer guide.

Categories

Resources