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
Related
I'm working on an app that keeps communicating with a device by Bluetooth(ble) when it's in both foreground mode and background mode.
I know I should implement ble jobs in a foreground service in Android, but the app is written in flutter and all codes are in dart.
It seems that for now even though there isn't a foreground service, the app keeps alive in background mode.
But I want it to be alive as long as possible.
So I'm thinking about making an empty foreground service...
Will an empty foreground service make an app has some priority in background mode?
And is it ok to do so?
Thanks.
The system can terminate an application in the background at any point. In practice if there is no need for its resources, it runs several minutes maybe more.
When using a foreground service, at some point only the service will run, so there is no real use of "empty service". Closing the application manually will leave only the service running.
Yes, an "empty" Foreground Service will usually prevent the app process from being killed automatically by the system, unless the device is critically low on memory.
How the code in the service class itself looks like does not matter. The important thing is that when a Foreground Service is running in the app process, the whole process will be prevented from being killed. This means that you can have Dart threads in the same process that won't be killed. Activities belonging to the same process that are in the background can still be "destroyed" though, i.e. the onDestroy callback can be called.
Since BLE connections in Android uses the Binder mechanism which are not tied to any of the standard Components (Service, Broadcast Receiver, Activity, ...) that otherwise control how the app process stays alive, having an "empty" Foreground Service is actually a common way to keep BLE connections alive.
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'm fighting with the Android desire of killing everything which isn't active on the screen. My problem in few words:
I have a microcontroller which communicates with a processor on which Android runs;
the processor must keep active a watchdog on the microcontroller, resetting periodically (every one second) one of its registers; an application, say App B, accomplishes this duty;
on the processor I can be sure about the persistent existence of another application, say App A (or, however, if App A dies App B can die too because the system is compromised) which for now does nothing, in the future will accomplish other duties.
Which is the best way to implement App B?
I tried the following solution: App B contains a Bound Service, say Service A, to which App A can bind on; Service A starts a thread, say Thread A, which periodically resets the microcontroller watchdog. Thread A is launched when app A sends a command to Service A (e.g. START_WATCHDOG).
In my idea, Service A lives until App A lives (thanks to the binding), and so the process to which Service A belongs lives, and so also Thread A.
Unfortunately, from tests I see that sometimes (in a sporadic manner), after some time (sporadic time, too), with almost no work running on the system (except for App A, Service A and Thread A) the system kills Service A process, and so Thread A stops and the watchdog elapses.
When Service A dies, it is restarted (because it is a Bound Service and App A is still running) but, for now, I don't save the current state of Service (which simply consists on the START_WATCHDOG command arrival or not) and this is the reason for which the watchdog elapses.
So, I've got several questions about my solution:
is it ok and I simply need to save the current state of Service A in order to restore it when restarted?
should I discover better the reasons for which Service A, or better its process, is killed?
is there a better solution for my problem?
Thank you very much to everyone who will spend some time to help me.
Being not sure about periods in which your service runs you can try these:
Use foreground service. However, you might need to acquire a wakelock within your service start point if you need cpu in long time. Plus, a notification needs to be shown on phone status bar.
Use WorkManager-new api part of jetpack simplifying the use of alarm managers and jobschedulers- to schedule your tasks periodically. However if your frequency is higher than 1 per 5-10minute then you will need to take care of doze mode. If phone gets into doze, your tasks might be delayed till maintenance periods. A trick to apply here might be starting a foreground service when you catch activation of doze mode and return back to Workmanager logic in deactivation(if you don't want user to see the foreground service's notification). Do whatever you want in the foreground service like.
Use Firebase Cloud Messaging to push notification from your server to your users periodically for you to have a small amount of time to do work in background. When notification comes, OS grants you an interval to run a task.
Use Work manager it is easy to implement.
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.
What happens to a service started by BOOT_COMPLETE after system kills it for memory?
Will it ever be restarted without rebooting the phone? Is it possible to restart it somehow?
What is the best practice to avoid as much as possible an important service from being killed?
Will it ever be restarted without rebooting the phone?
Possibly. If it truly was because "system kills it for memory", and you return an appropriate value from onStartCommand() (e.g., START_STICKY), it should be restarted at some point in the future. If the service was killed due to user action (e.g., Force Stop in the Manage Services screen in Settings), it will not be restarted.
What is the best practice to avoid as much as possible an important service from being killed?
First, design your application to not rely on an everlasting service like this. 99.44% of Android applications do not need a service that runs continuously, let alone one that starts doing so at boot time. Android device users hate developers who think that their apps are sooooooooooooo important that they have services running all the time -- that's why we have task killers, Force Stop, and Android killing services due to old age. For example, if you are checking for new email every 15 minutes, use AlarmManager and an IntentService, not a service that runs forever.
If you can demonstrate -- to me and to your users -- that yours is among the 0.56% of applications that really do need a service that starts at boot time and runs forever, you can use startForeground(). This will indicate to the OS that your service is part of the foreground user experience. You will have to display a Notification, ideally to allow the user to shut down your service cleanly if and when the user no longer feels that it is justified.
If you need to restart the service then you should use AlarmManager to check up on the service in a separate BroadcastReceiver, but nominally when a service is killed by the system for memory it will not get automatically restarted.
You may want to take a look at START_STICKY
Use the AlarmManager to periodically send an Intent-- receive the intent and make sure your service is running.