I'm wondering what you can do programmatically to minimize the footprint that your service will have on a device? Are there any particular tricks to the way that you write a service so that it doesn't take up much system memory? I guess low memory footprint is my main concern so that a user does not want to turn the service off and is willing to have it always running.
***EDIT***
Okay so reading the answers I"m thinking that I must be doing this wrong. I am using the AlarmManager to periodically wake the service up but I am not ever stopping the service unless the user indicates via the main activity. So should I include at the end of my onStartCommand after my service performs what it needs to should I call stopService? Doesn't stop service call onDestroy because if it does I was deregistering my AlarmManager in onDestroy.
The way that it runs right now when I go to running services on my phone it has the service running but it is not actually doing anything until the AlarmManager goes off at which point it performs it's small function and that's it.
I guess low memory footprint is my main concern so that a user does not want to turn the service off and is willing to have it always running.
Theres a huge one for optimization. Androids services are not meant to run all the time (like Windows services or unix daemons).
They are more like a task solver, e.g. download a file. After finished with their task, they should call Service.stopSelf().
If your app needs the service again, it should restart it then for the appropriate task.
It really depends on what your service is doing so there's really no right or wrong answer. The important thing that I try to stay mindful of is not to keep the service alive for any longer than is required. If your service spends most of its time in an idle state, then consider waking it periodically with an alarm, and stopping the service once its periodic work is complete. This has the added benefit of preventing many task killers from destroying your service if it doesn't stay running for very long.
I also try and use inexact alarm as these are generally kinder on batteries, and battery life is also something that you should be mindful of.
In terms of memory footprint, it is always worth freeing up any unused resources, and keeping your code as lean and mean as possible, whether it is in a Service, Activity, Receiver, or anywhere else. Although current smart phones have considerably more memory than feature phones, Android is increasingly being run on comparatively lower spec hardware, so it's worth being mindful of lower end devices.
Reto Meier has recently written some articles which cover these sorts of topics on his blog.
Related
what service class should I use for the stopwatch that will run on the background
Which one should I use in terms of performance.
You should use foreground service (with Service instead of IntentService) in this case.
Reasons:
Android Oreo 8.0 defined Background Execution Limits. So you will not be guaranteed of service life.
Your app is also killed in Doze mode & Standby .
If you are running a continuous service with a long thread & start-sticky then your app is being suspected by optimization apps and OS. Your app will be considered battery draining.
Intentservice kills itself when work is done. Whether normal Service fits your requirement where only you have controls of your service.
Solution:
As i said make normal service as foreground service. See here. That will notify user till your service is running. And it will not be killed by OS due to any above reason.
Here is an old question with loads of answers regarding differences between Service and IntentService. Maybe you can find something there.
From personal experience i'd say they are not that much different. Just the way you use them. I would say stick with the one you think fits your application best overall.
Service vs IntentService
I am trying to create an Android app that shuts Spotify and thereby turning off music after you fall asleep.
The user gets to choose how long to keep the app running. My question is, can I kill background apps from my current app.
I tried looking on Android Studio's developer website and Google but could not find the answer I was looking for. Thank you.
Service runs in your app process. If your app is garbage collected, the service will stop until:
You start the service in new process via manifest file declaration
You make the service sticky (recommended).
go ahead and research above two and let me know if you would like more explanation or code
If you see official documentation of Service, Google clearly explains why and when service will be destroyed. What is useful in your scenario:
A started service can use the startForeground(int, Notification) API
to put the service in a foreground state, where the system considers
it to be something the user is actively aware of and thus not a
candidate for killing when low on memory. (It is still theoretically
possible for the service to be killed under extreme memory pressure
from the current foreground application, but in practice this should
not be a concern.)
using startForeground will ensure your service keeps running in the same process. some pointers:
A service with attached client will not be destroyed even on low memory scenarios
A service will be killed in low memory scenarios, regardless of the process. Running in a different process is better but does not guarantee it won't be destroyed by system.
Don't use system.exit(0) to end your app. call finish() on activity.
Starting sticky service just ensures that service is restarted when memory is freed.
hope it helps!
I want to have various asynchronous threads in app like around 5-10 threads for background tasks which can be long running (like streaming) and I am also updating the UI to post some results if necessary.
From what I have heard that AsyncTask has problems with:
Long running tasks,
Having poorly being tied to Activity life cycle,
Device orientation problems, and
Memory leaks and so on.
So, I am looking an alternative (possibly without using any third party libraries) which doesn't have these above problems.
Should I be better off with using Simple Java Threads? I don't mind using them given that they won't give any problems that are with AsynTask.
In most scenarios AsyncTask should suffice the requirement. However there are scenarios where AsyncTask can't be used. ie AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Now the thread pools assume that they'll get their threads back after a reasonable period of time. So in a scenario where you do not know how long you'll need the thread you can't use an AsyncTask. And as of Android 4.4 , the size of thread pool can grow only to : (no of CPU cores * 2) + 1. So on a dual core processor, the maximum number of threads you can create is limited to 5.
So, I am looking an alternative (possibly without using any third party libraries) which doesn't have these above problems.
Coming to the alternatives to AsyncTask, these are the available options:
Handler
Runnable
Now there are cons to all background threads no matter how beautifully illustrated they are, few include:
The possibility of user's interaction while the background thread is processing. If the work that the background thread performing is altered, you'd need to communicate it back to the background thread. java.util.concurrent has many classes to help in these scenarios
The possibility of the process itself being killed while the thread is performing tasks. So in these cases instead of using an AsyncTask or the simpler Thread a Service or IntentService would be an ideal option.
The possibility of an error occuring inside the background thread, such as retrieving data from server while connectivity is lost, you'd need to manually shut down the background thread.
In short: Whichever option you choose, you'd need to manually handle
all corner cases for the efficient and splendid working of the app.
PS:
[Citation] : The busy coder's guide to Android development v5.8 by #Commonsware which is released under the Creative Commons Attribution Non-Commercial Share Alike 4.0 License
Long running tasks,
Having poorly being tied to Activity life cycle,
Device orientation problems, and
Memory leaks and so on.
Simple java threads are not going to solve any of these problems. Specially, memory leaks.
If you just want to load data in background, you can think about Loaders. They cache the data application wide and fit nicely with activity/fragment life cycle.
Alternately, you can go through this article to know about services (if you don't know already) and see if they are suitable in your scenario.
I would first suggest to use the above mentioned components,
Handlers
Runnables
If the operation is long running then you can go for service as it runs continuously. You said
which can be long running (like streaming)
If you are streaming over some audio or video then it is best to use a service either a normal Service or an Intent Service depending on your requirements.
You can destroy the service when ever needed or let the Android system do it when required.
Hence I would suggest you to use a Service in such a scenario.
My java desktop application runs every time the computer starts up and runs as long as computer is ON.
It monitors all the activities and interacts with database more often and will tell me some updates by looking on the internet at regular intervals etc..etc..
So what I usuallly do is creating the threads and calling the sleep method. BUt is there any way so that i can handle the memory more efficiently as my program runs 24/7. Are there any methods which will be very much useful if we want to make the program sit silently if there is no job to do . Any advice or suggestion will be helpful
Thanks in advance
Only allocate as much memory as you need, in other words, do not keep stuff that you do not need.
Also, run at lower priority; though with sleep-calls, this won't gain you much.
Of course you could, or depending on the kind of application, should, also quit the program after doing the job, and only let it restart by cron, anacron or similar services (depending on your operating system).
I think you could use a Thread pool for your tasks,
This hold some threads active and when one of your tasks needs a thread you can request one, this way you need less active trheads running
Oracle about thread pools
I have 5 IntentServices that run at different times and in a separate process than the main UI. When the services complete they send the data via an intent to the main process. I am wondering if having 5 services is using too much memory for my application. Are services completely cleaned from memory when they shutdown or are they still allocating memory.
Thanks
It seems each service consumes some memory. Here is good discussion on this topic. Android service components facts
An IntentService automatically shuts down when there is no more work to do. After that, it should be eligible for garbage collection, assuming you have not done something to introduce a memory leak.
That being said, I would think it makes more sense to have one IntentService that performs all five functions, examining the incoming Intent to determine which thing to do.
You got nothing to be worry about, Android OS running dozens of services at the same time, it is completely safety.