Android services: life cycle considerations - android

I am making an android app which will have two services that will keep sending data about the usage of the phone by the user every 24 hours.
The user should execute the app, toggle the buttons to enable the logging of the usage of the phone and then the user should be able to do a normal life with his phone, until he starts again the app and disables the toggle button to stop the logging of the info.
What considerations should I take about the life cycle of the services?
What about the interaction of the user with the phone while the services should be sending the data?
All info is very much appreciated, as I my mind is getting a little bit overwhelmed with all this!
Thanks a lot in advance everybody!

The service can be cut at any time through the settings menu. It can also be killed at any time by Android if it decides it needs the resources for the currently running activity. onDestroy() will be called regardless so use that to store anything needed.
The service runs in the background but through the main UI thread. Thus, it is possible to block operation of the phone through a service. It looks like the phone locked up when it's really a service trying to do something. Any blocking procedure should be used in a thread such as Java timer, Java thread, or AsyncTask.
There can only be one running version of the service at any given time. However, calling startService(myService) if "myService" is already running will essentially override the current running service and onStartCommand() will be called again. However, one call to stopService(myService) is needed to stop it no matter how many times startService(myService) was called.
stopService(myService) will not stop a service if the service is bound to anything. It will wait until all bindings are removed before the service stops.

Related

How to have a continuous running background task on Android?

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.

Android:nonstop Back ground service

I have started a service from my application and from that service a worker thread is started .I want my service to run even application goes background and until the user kills/exits the application.
But some cases my service got killed due to low memory ,then used sticky service or making the app to foreground to restart the service.
My issue is I dont want to lose the data between service ending and restarting time ,so is it possible to start another thread from service ondestroy method, but in this case how we can control that thread.
Please let me know is it the right approach ,and is this usecase achievable
I want my service to run even application goes background and until the user kills/exits the application.
This is not possible. The user can always get rid of your app, via Force Close in Settings, or via some device's version of the recent-tasks list.
But some cases my service got killed due to low memory
No, your process is terminated for low memory.
My issue is I dont want to lose the data between service ending and restarting time ,so is it possible to start another thread from service ondestroy method
No, because your process is being terminated.
Please let me know is it the right approach
Probably not. Very few apps need a service that runs constantly, which is why Android, and its users, go to great lengths to control such services. I would recommend that you try to find some solution to whatever your problem is that does not need a service running constantly.

Can user starts an application with screen off?

In my application I check to the server some user state in the onCreate() method of the main activity.
I recently notice that doing so is an issue when I run the app from Eclipse while the phone is asleep (screen off, locked). In this situation, the application waits that the screen get unlocked to call the onStart() method and pursue its way. That makes fail the data update.
Maybe I should put it inside onStart?
Can the user do the same process = start an app with locked screen? I though of Tasker but are there other way?
Edit: All the server updates communication are done off main thread, handled by managing classes and I use volley. So it's not a service and though I will put one later, I have not enough time to do it now. Except if you say it's 2 days work to learn and implement. Can a user start an application like a dev can do it ?
This things that you are doing in an Activity must surely be performed in a Service. Android Service provides you with doing background data processing/syncing.

how do I make an android service that runs when the application doesn't?

my knowledge of services in any operating system, is that they usually run in the background and perform whatever work they have to do.
but the first time I got familiarized with android services, I got confused.
it appears they only run when the application is working, and that for me, makes them no more then sophisticated threads.
do I have this all wrong? how do I make a service that runs when the application doesn't? (so that I can check for updates and create notifications for the user that will then lead him to the application if he chooses to open them).
does push notifications have anything to do with it?
Edit:
thank you guys for your answers so far.
my problem seems to be the fact that the service is only started officialy when the device is booted up. I do call startService when the app starts, but that doesn't seem to help. the service still dies when the app is turned off (unless it was booted)
also I never call stopService
If you are trying to implement a long running task that is performed in a (background) service, you have to start one or more threads within your service. So the service just gives you the opportunity to have an application context without having to have a user interface ;) you can consider it as a kind of container.
This page give you a nice overview about different thread approaches in Android. As you can see a service has not its own thread.
Anyway, in your case it seems that an AlarmManager is probably the better option. Running services for polling information all the time can be quite CPU and battery consuming (see this post for instance). So try to avoid having threads that run all the time.
If you can push information about updates from a server it's just fine. Check out Googles Cloud Messaging in this case.
Michael who commented on my question first was right in his comment about startService()
so it goes like this:
my receiver is only activated on boot, and uses an AlarmManager to
time the service to certain intervals.
what I did was to bind the activities to the service. if the service
was off and I binded it and unbinded it, then by the time the app was
terminated, there was nothing keeping it alive.
by simply making sure that the service was started properly with
startService if it is not already on, I managed to keep the service
alive at all times
also thanks to Trinimon who gave a very nice explanation on what
services are, and the importance of not overloading the CPU with
excessive polling. (which is kind of a trade off situation)
good luck to all :)

Android Connect to Running Thread

I am creating an app that has a UIThread and a background thread. The background thread is basically being used as a timer - every second it sends a message to the UIThread to update the UI. When the user exits the app by hitting the backbutton, the thread continues to run. I want this to happen since the user may want to open another app while the timer continues to count down.
My question is when the user comes back to my app. I want to connect to that background thread that is running to display the current state of the app - how much time is left, etc. My question is how to hook back in to the thread that is still running in the background. I have tried using Thread and AsyncTask, but the same issue occurs.
Thanks for any help that you can provide.
Your thread is still turning by sheer chance - your application is in fact still running but it and the thread will be shut down when Android decides it needs the resources.
However what you want to do is well-provided for in Android - you need to implement a Service to have a process that runs in the background separately from your application. You can even have a Service start at boot and run whether or not your application is started.
This http://developer.android.com/reference/android/app/Service.html has most of what you need to know. To communicate between the Service and a foreground Activity you'll need to bind to a service interface, which is fortunately very easily done.
First thing that comes to mind is to change your timer thread to a Service and have apps interested in it bind to that service. Based on the Android documentation and suggested app design, you cannot depend on that thread to not be killed by the OS whenever it deems necessary.
http://developer.android.com/guide/topics/fundamentals/services.html
The android system provides a broadcast event every minute, it's call TIME_TICK.
You should:
Create a service. This is the recommended way to have a part of the app running in the background
Listen to the TIME_TICK event. This will consume less battery. (It won't wake the phone, though, so use an ALARM, too)
Add an alarm (to wake the phone if necessary)
Let the UI and the service interact. You need a callback via rpc (see the last callback example on the api page)
You should also ensure that the phone can sleep during the timeframe. You thus may want to compute the state as a delta between the starting point and now, instead of updating the state all the time.

Categories

Resources