I have an Android application which supposed to be active in the background all the time. I've built it as normal Android application. It works pretty fine, however, sometimes it stops by itself (or by Android OS) and have to re-run it. It's not because of an error caused, this is because it's a normal application, perhaps.
How do I make work all the time in the background?
UPDATE:
the application has GUI.
Android OS may terminate a process at any given time due to memory constraints, you can learn how Android manages memory here. As #Karakuri mentioned starting a service would make it much less likely to be terminated, another plus for using service is that even in the event that it is killed the OS would try to resurrect at a later time when memory constraints permits:
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 this
happens, the system will later try to restart the service.
You can learn more detail on Services from the Android dev site.
Create a Service and call startForeground() to make it a foreground service. It doesn't prevent it from being killed, just makes it less likely as Android will try to keep it alive longer than non-foreground services. Note that you need to place an ongoing notification with an icon on the status bar when using a foreground service.
Assuming you are using a Service. If you return START_STICKY from onStartCommand() of service, then even if android has to terminate that service, it will be re-started as soon as the resources are free.
Related
I have written an VPN using android's VPNService and it works perfectly. When I run it, it creates a foreground service and sends all traffic through my VPN server. It also has an internal reconnecting mechanism to reconnects VPN server if it disconnects for any reason without stopping service itself.
I like to have this VPN service working all the time. But my problem is that this VPN service is stopped occasionally after a completely random period(sometime it takes just 10 minutes, but other times it works for 2-3 days before stopping).
Since the stopping time is completely random and I cannot find any place in code that creates this situation (I have been debugging for weeks), I thought maybe android OS itself stops my VPNService for some reason. I wonder if there is a way to detect if system has stopped my service from outside or not. Any idea?
Unfortunately, Android OS still can terminate the service in low memory and possibly other situations, even if it's a background running service !
It is not only Android, but all Mobile Operating Systems optimize RAM usage by killing background apps.
This is done so that the foreground app can be given top priority. It ensures smooth functioning of the current app and reduces load on the system.
There's are two approaches as mentioned in this post: Background Service getting killed in android
If you are implementing the service, override onStartCommand() and
return START_STICKY as the result. It will tell the system that even
if it will want to kill your service due to low memory, it should
re-create it as soon as memory will be back to normal.
If you are not sure 1st approach will work - you'll have to use
AlarmManager
http://developer.android.com/reference/android/app/AlarmManager.html
. That is a system service, which will execute actions when you'll
tell, for example periodically. That will ensure that if your service
will be terminated, or even the whole process will die(for example
with force close) - it will be 100% restarted by AlarmManager.
I had this issue previously and I've solved it by creating the service running forever even if it's killed manually or from the system it recreates itself.
I have read many posts state that doze mode killed a running service at a particular moment e.x link or that they want to execute a long running thread.
I can't understand why you should use a service to do a background job that you know that in some point it will stop eventually.
For instance:
You could use a simple Thread:
new Thread(new Runnable).start()
and do some work in it. Using this:
In combination with a wake lock, device wont sleep and thread will keep running.
No doze mode restriction (except network but lets say we do local stuff)
So you can do background work with no restriction whatsoever. Although you should use services for these reasons link.
Is this another way (not better of course but a way nonetheless) of doing a background work? Am I wrong?
There are a lot of ways to do a background job aside of services check this link it may help you pick the best option for your work :
Job Scheduler vs Background Service
And services as #TheWanderer said will continue to work event after the app is closed for a period of time unlike a simple thread that will end immediately when the app is closed.
Read this part in the link that you linked
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
If you are running a background thread that you start from an Activity, Android does not know that you are doing background work in the OS Process that is hosting your Activity. Android can kill the OS Process hosting your Activity at pretty much any time. If the user presses the HOME button or takes a phone call or opens a notification and goes to another application, Android can kill off the OS Process at any time. When the user returns to your application, Android will create a new OS Process and recreate all the relevant activities, but your background thread is hopelessly lost. This is the reason that Android has services.
If you start a Service to perform your background processing, the Service will also start background threads, but these are controlled. Your Service tells Android what to do if it kills the Service while it is processing an Intent. Your Service can therefore be informed and restart (or continue) the background processing as necessary. You can also run the Service in a different OS Process from the OS Process running your activities. This will prevent Android from killing the Service if the user removes your app from the list of recent tasks.
With newer Android SDKs there are other mechanisms you can use, like JobScheduler.
I am working on an Android project and I need the app to work even when the device is locked.
The idea is to open the app that will start the (Intent)Service, the service processes the data all the time. The device can be locked/put away and after some time when the app is opened the service is manually stopped. The service should be running all the time in the background.
I have found information online, but I am not sure what to use and in which way..
I have found that the IntentService can be used. Also the service should run in a new thread. I need to process the data from gps all the time, should I use WakefulBroadcastReceiver?
Thank you.
IntentService is not necessarily what you want to use. It will automatically spawn a new thread just to handle an incoming Intent. Once all incoming Intents have been handled it will stop the Service. To have a long running Service, you would need to derive from Service and when it is started return START_STICKY from the onStartCommand() method, plus spawn your own thread to handle your background work.
If you need to monitor GPS, you'll have to manage that along with keeping the device awake using a WakeLock. Note that in Marshmallow, this gets more complicated because of the new Doze mode where even wakelocks are ignored.
Also, note that the way Android is architected there is still a chance that your application running the background Service may be killed. Android uses a unique process management technique based on memory pressure and user perceived priority to determine how long a process should stick around. I recommend reading up on the Service lifecycle in the documentation.
In android their is no fool proof way to ensure that your service runs forever because the LMK(low memory killer) when the system needs resources (based on a certain memory threshold) , kills the service then if it can restarts it. If you handle the restart properly the service will continue to run.
Services that are given foreground priority are significantly less likely to be killed off, so this might be your best bet. However their will be a notification of your service running the in the background on the menu bar up top. Foreground Service
I don't know much about Android multitasking but I thought I'd ask the question before I attempt my project.
Is there a way I can program an Android application (aimed at Android 4.0+ only) to always be open in the background and keep all the network connections alive and the UI "drawn" so that when I open it, it ALWAYS opens instantly and I can use it instantly even if the tablet is doing something else?
Thanks.
Most likely, you want to create a foreground service. A foreground service is a service that the user is aware of and is not considered a candidate to kill if Android is running out of memory. It is associated to a persistent notification bar, that the user can tap to bring to the foreground an activity. To make sure that the network connection are not switched off, your service should acquire a wake lock.
However, please remember that a long running process that potentially kills the battery is considered a bad practice, and you should avoid doing this unless you have really really strong reasons to do it.
No, Android is not build like that. The OS can always kill services/activities in the background when it needs more resources.
You can make services which are always running (sticky service) which restarts if it is killed because of resource problems, when there are resources again available.
With Activies you cannot do that. But it could be happen that your activity is 'paused' and still in the background, so it can be 'resumed' very quickly. But again Android can easily kill it for resources.
There is no way you can have an application always running in the background, unless you modify Android at the firmware level and build your own version. Android kills other apps as and when it needs more resources to run the app currently in the foreground.
However, it is possible to make your app better at handling this by saving data and it's current state in onPause() and restoring the same in onResume().
how to prevent our process to be killed by Android System while low memory?
You probably should not do that, and properly implement the lifecycle methods instead. Are you absolutely sure your application needs to do that?
Services has higher priority than Activities.And it will be restarted automatically when android get enough resources.
If your app does not need user interaction continuously,I think that's what you want.
If you need something to run in the background, you need a Service. A Service is less likely to be killed by the OS than a background Activity. Still you should expect that it will be killed, that is the design of Android. You can use the AlarmManager to frequently restart a Service if it has been killed, so that very little time passes without your Service running.