How to keep android service always running? - android

It always seemed some sort of black magic the way other apps keeps their services always running, but mine gets killed by the system every time.
My app should keep a TCP socket open to the server and send/receive data when it becomes available, so it has to stay always on.
This is what I have tried so far:
1) Running the service in another process using this line (also with an additional line stopWithTask):
android:process="package.name.custom_process_name"
android:stopWithTask="false"
2) Restarting the service when these methods get called:
onTaskRemoved()
onDestroy()
3) Add return START_STICKY to onStartCommand() method
4) Check if the service is still running when these events happen:
android.net.wifi.WIFI_STATE_CHANGED
android.net.conn.CONNECTIVITY_CHANGE
- Here I am stopping the socket connection to the server if the device does not have internet connection anymore and reopening it when it gets a connection.
Yet, my service always gets randomly killed (sometimes after few hours, sometimes after few days) by the system and doesn't restart automatically until I reopen the app.
How does other apps, say chat apps for example, keep their services available all the time?
P.S.: Having a persistent notification would be the least of options.

Override onDestroy() in your service, whenever your service destroys create Alarm using AlarmManager. When alarm trigger start your service again.
Second way is not recommended or proper way but create a separate service AlwaysAliveService which will do nothing but will remain available in android system.

Related

How to find out if android OS is stopped Service

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.

Create a Long Running service

I need to create a service that runs alongside the android app,irrespective of which screen of the app the user is on.
The app is a chat application so when the device is offline the service should queue up all the messages that are being sent offline and when the device is connected it should sync all messages.
I have written code for the job scheduler to sync data automatically when the device is online but while the app is active i would like to handle this manually.
Creating a Long Running service.
Operating system still can terminate the service in low memory and possibly other situations. There are 2 ways to overcome this:
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.
AlarmManager .A system service, which will execute actions 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.
Thank you.
You can do this by simple following steps:
Create Simple Service and after first launch of app just start at splash screen.
In Service after getting one data you can call another request.
After that you can create one broadcast action globally which will always call every network changed.
At background you can sync again data and saved it to shared preferences or as per your your requirement.
For interval you can also using AlarManager.
A part from this you can simply create Service using JobSheduler in this you can assign job and time as well.
Refer link :
https://developer.android.com/reference/android/app/job/JobScheduler.html
Hopefully this logic will helps you.
You have to use a intent service with sticky instead of service for this which will be executed in a queue and do your work. And since it is a intent service it will be started automatically after sometime, when system kills the service process.

Service doesn't stop when exiting app by press of the back button

In my app, a Service is started in the background to handle BLE communication with a BLE device. I have an Activity (StartActivity) on start of the app which searches the BLE device and when it found it, it starts the Service (BleService), hands the found Device to it and then binds to it to receive Broadcasts from BleService.
BleService establishes the BLE connection, sets notifiers on different characteristics and reads them. As it got all the information it initially needs, a Broadcast is sent.
This Broadcast causes StartActivity to switch to another Activity (MainActivity), which then binds again to BleService and reacts to BleService's Broadcasts.
So far, so good.
When I press the back button while in MainActivity, the app 'closes'. Now, when I restart the app (either by clicking on its icon or in the recent app list), the app gets back into StartActivity and can't connect to the BLE device. As the LED on my BLE device is constantly signalling me, it's connected, I think the first BleService is still running and connected to the BLE device.
I checked this by adding a Log output to BleService's onDestroy() method and yes, onDestroy() isn't called. It is called, when I close my app through the recent app list.
What should I do when closing my app through the use of the back button?
EDIT: So I want to destillate my problem out of my question:
When I close my app on pressing the back button in MainActivity and then start it through the recent app list or via its icon again, I get stuck in StartActivity. This is, because StartActivity can't find the BLE device, as it is still connected to the still running BleService.
How can I avoid this?
I am not sure what you want to have happen when "back" is pressed, but you can take a look at this answer to help you determine if the service is running or not and take appropriate action.
If your client and server code is part of the same .apk and you are binding to the service with a concrete Intent (one that specifies the exact service class), then you can simply have your service set a global variable when it is running that your client can check.
We deliberately don't have an API to check whether a service is running because, nearly without fail, when you want to do something like that you end up with race conditions in your code.
An Android Service is meant to remain running even when its parent application terminates. This is an important function to be able to execute any critical operations even when the application crashes/closes/gets killed...
For you, this simply means that you have to close your service upon quitting your app, at least if this is what you intend to do. Doing this is very simple:
stopService(new Intent(ActivityName.this, ServiceClassName.class));
If you are starting your Service via Context.startService() then it must be stopped via Context.stopService() or the service itself calling stopSelf(). Binding/unbinding to the service will only stop it if the binding was how the Service was started in the first place (e.g. not using startService()).

Keep a Service started at BOOT running even if Application stopped

I am working on a app that during boot time starts an activity that logs in to my server (needs an activity to log in through facebook) using a service (initiated with startService). This service establishes XMPP listeners and does nothing after that, just waits for connection. I want this service to run all the time the device is up.
The problem is that the activity stops after a while and my service is also stopped. The service returns START_STICKY so I was expecting it to hang around. Also the service doesn't do anything except wait for connection.
The activity has the properties:
android:excludeFromRecents="true"
android:noHistory="true"
android:launchMode="singleInstance"
so that it does not show up in the task list (when user long presses the home button).
The activity is stopped when the user long presses the home button and the service also ends. I am thinking its possible that the application exited, that's why the service also ends. I could not find any way to keep the activity from not stopping. Maybe its stopping because of the above properties.
So what can I do to keep the service running all the time. How can I keep the application from being removed. I read somewhere that if I keep a while loop running in the service then START_STICKY can keep the service around??
I can use AlarmManager to start the service but I don't want it to stop easily and then have to restart it every time.
I don't want to run a foreground service. I can not run the service in a different process since I am using existing code that does not do IPC. Any help will be appreciated. Thanks.
There are two things to keep running a service indefinitely; create the service using startService() and return START_STICKY from onStartCommand(). You seem to be doing this both. With these two steps, the service may be shut down by the system but it should restart almost immediately.
The only suggestion I have is to create a separate thread in the service. This is because by default, started services run in the application main thread. If the service is constantly doing certain task, it may block the main thread and kill the application. Google doc has an example of implementing this:
http://developer.android.com/guide/components/services.html#ExtendingService

Android Service restarts randomly

I'm trying to write a Service which sits and waits for SMS messages (using a BroadcastReceiver which the server registers) and will take some action depending on the details of the SMS message. I use an Activity to startService() and stopService() for the Service. After I close the Activity, the Service continues to sit there with its state kept and its BroadcastReceiver waiting, as it should... However, I find that over time, randomly, the Service will restart itself. That is, onCreate() and onStartCommand() will be called even when the Service has already been started. This happens sometimes when my phone sits idle overnight...
Can anyone provide insight on why this is (phone requests resources and kills a service?), what I can do to prevent it, or what I can do to prevent the state of the service from being lost?
Thanks in advance.
I don't think you need to start service from activity at all. Have a broadcast receiver that listens to your SMS messages and starts the service. After work is done, service should call stopSelf();
I'll try Service.startForeground()
Android sometimes (when it's low on resources, mem/cpu) removes running services and once it's high on resources again brings them back. This is why you see that your services has been restarted a couple of times during night.

Categories

Resources