I'm building a monitoring app that will capture as much info as possible from the mobile device, like running processes / active connections / networking statistics / active interfaces etc. Obviously I will need a service that will be running in the background for that, but I'm not entirely sure how to implement it.
Someone suggested that I create an IntentService that will execute at specific intervals using AlarmManager, do its thing and then die again.
In this thread people suggest an implementation using an always-on Service that starts its own thread to do the work, put it to sleep and then again. One also suggested that AlarmManager is used too to make sure that the service will be restarted if the OS kills it.
What's the mpst appropriate implementation for monitoring real time data? (or the up/downsides of each). Note that many of the info I'm capturing do not produce intents (so I can't just register receivers)
Thanks a lot:)
Note that many of the info I'm capturing do not produce intents (so I can't just register receivers)
Then you won't be able to use an IntentService, since your app won't know when to fire it up.
If you want "real time" updating of info, then you will have to use a Service (with or without it's own background thread). You cannot use an AlarmManager because it will almost always run too late (not "real time").
Do note that it takes some effort to have your service run always as there are a couple of different scenarios where it can stop running, and even when you have done all you can to achieve it, there are still ways for OS or user to stop it from running.
Related
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 :)
I would like to create an Android application with real-time monitoring functions. One monitoring function is to audit the audio flow. The other function is to interact with a peripheral sensor. These monitoring functions can be triggered by others.
Besides, in order to save power consumption, the audio function will be running in a polling mode, i.e. sleep for a certain amount of time and wake for a certain amount of time.
I am considering how to design the Android application.
Whether to design the audio function as a Service or an Activity?
The problem is if it is designed as an Activity, the audio function will be off if screen turns off after a period of time.
How to design the polling function? Use an AlarmManager or a inner-thread with Timer?
My goal is to save the power consumption as much as possible. Thanks.
I would recommend following
a) Use a Service. Activity is short lived entity (it works only while it's on the screen)
b) Make the service foreground (read this: http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification). This will decrease the chance that system will kill your service
c) In the service, start a thread and do everything you need in the thread.
d) If you want execute periodically, just do Thread.sleep() in the thread (when Thread sleeps it doesn't consume CPU cycles).
I believe c) and d) is preferable to AlarmManager.
Here is piece from documentation (http://developer.android.com/reference/android/app/AlarmManager.html) : "Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler."
Since your application running it's better to have some permanently running thread and execute something on it. Generally speaking Handler, HandlerThread, MessageQueue are just convenience classes for more complex message handling and scheduling. It looks like your case is quite simple and usual Thread should be enough.
Concurring with Victor, you definitely want to use a Service, and pin it into memory by calling startForeground()
However I suggest you look into utilizing the built in system Handler ; place your functionality in a Runnable and call mhandler.postDelayed(myRunnable, <some point in future>) ; this will allow the android framework to make the most of power management.
That's a service.
And you may want some extra robustness: the service can be killed and NOT restarted later, even being a foreground service. That will stop your monitoring.
Start your service from the UI. If you want the service to survive device reboot, also start it from a BroadcastReceiver for android.intent.action.BOOT_COMPLETED.
Create a thread in the service as described in other answers here.
Additionally, use Alarm Manager to periodically start your service again. Multiple startService() calls are OK. If already running, the service will keep running. But if it's been forgotten by the system, say, after a series of low resource conditions, it will be restarted now.
Schedule those alarms responsibly: to be a good citizen, set the absolutely minimal frequency. After all, Android had some good reasons to kill the service.
With some services, even more steps may be needed, but in this case this approach seems to be sufficient.
I need to run a background service in Android mobile which runs 24*7, And on Start & On mobile low battery and Hit a webservice every 1hr. Can you please suggest me any approach. I tried reading few articles but did not get any idea. I know here I need to paste some code after trying something. But I did not get any clue. Please let me know how to approach?
You will probably need to use the method startForeground(int id, Notification notification) to prevent the system from killing your Service as stated here:
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.)
Then you would need some kind of scheduled task to run every hour. Something like a ScheduledThreadPoolExecutor is ideal for this purpose, using the method scheduleAtFixedRate (Runnable command, long initialDelay, long period, TimeUnit unit).
The task that needs to be done each hour must be implemented as a Runnable and submitted to your ScheduledThreadPoolExecutor:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 );
executor.scheduleAtFixedRate( new MyRunnableTask(), 0, 1, TimeUnit.HOURS );
The Runnable task should be something like:
private class MyRunnableTask implements Runnable {
public void run() {
//Do what needs to be done.
}
I need to run a background service in Android mobile which runs 24*7
Please don't. For starters, it is not possible.
Users complain loudly and often about services that "run 24*7", because the services are tying up system resources (e.g., RAM) for no value. As a result, between third-party task killers and Force Stop options in Settings, users get rid of such services. When they do, particularly on Android 3.1+, your application will not run again, ever until the user manually launches an activity of yours from the launcher.
Android itself will get rid of such services on its own, because too many developers are too sloppy with their service management.
And on Start & On mobile low battery and Hit a webservice every 1hr.
Based on this list, you do not need "a background service in Android mobile which runs 24*7". You need to do work:
when the device starts up
when the device's battery is low
every hour
You can find out when the device starts up by the ACTION_BOOT_COMPLETED broadcast Intent. You can find out when the device's battery is low via the ACTION_BATTERY_LOW broadcast Intent. You can find out when time elapses via AlarmManager, where you establish your own alarm schedule (e.g., every hour).
All three of these triggers should call startService() on an IntentService. The IntentService will allow you to "Hit a Webservice" via its built-in background thread. And, the IntentService goes away when that work is complete, so you are not taking up memory all of the time.
And, if you want to wake up the device out of sleep mode for the every-hour condition, you will probably need to use something like my WakefulIntentService, as otherwise the device may fall back asleep while you are trying to "Hit a Webservice".
This way, your service is only running and taking up resources while it is actively delivering value to the user. It is not running and taking up resources when it is simply waiting for some other event to occur (e.g., the next 59 minutes).
I'm creating a service that runs in the background. It does the following:
Gathers the user's data (with permission)
Runs certain tasks every X minutes, and sends this data to a server every Y minutes
I'd like if other people could write their own UI, widgets and other cool stuff.
Currently, the service continues to run between task runs/network sends (without a wakelock).
The service listens for validation and runtime changes; this requires a separate process. There are ways around this but they would involve using IPC (which I don't think would cause a big performance hit).
Questions:
Should the service be allowed to die between tasks or should I let it run without a wakelock?
Is it more effective to remain alive than to open a database every minute or so?
Can people use my service if it's not in a separate process?
The question the arises, should my service be in it's own process?
No. By which I mean it should run in the same process as all your other components.
I think it'd be nice if other people could write their own UI, widgets and other cool stuff.
It doesn't have to be in a separate process for this right?
No. It will automatically be in a separate process from the code from the "other people".
Right now the service stays running between task runs/network sends (not keeping a wakelock though) as I figure it will be more effective than opening a database/doing setup every minute or so.
Your users may disagree with this plan. Everlasting services are the reason why users attack developers with task killers and force-stops from the Settings app.
Should it be allowed to die between or should I let it run without a wakelock?
I recommend that you use an IntentService (since you need the background thread anyway for the network I/O) and let the service shut down in between polls. Also, please allow the user to control the values of X and Y from your opening paragraph.
Tasks run on an interval, should my service die in between (having to reopen the DB)?
Generally, yes. Opening the database takes a very small amount of time (e.g., handful of milliseconds), unless the flash storage is busy. That is a small price to pay to avoid complaints from users about your service running all of the time.
Can people use my service if it's not in a separate process?
Yes, so long as you are exposing some API (AIDL, documented set of Intents to send as commands via startService(), etc.).
It seems to me it might be worth dedicating an app purely to the service (i.e., no other components except a 'settings' Activity) and do everything through Intents.
As long as the manifest has all possible Intents registered using <intent-filter> blocks, anyone can communicate with it (your own apps as well as any 3rd party apps).
Also, you might want to use an IntentService which will process commands as they arrive and then shut itself down when finished.
Without fully understanding your requirements, i.e., what exactly the service is processing, it's difficult to advise further.
I'm implementing an background process that will update information my app uses.
I only want this process to update say once a day, if the process gets data newer than what it had before I want to present the user with a notification, exactly like twitter/gmail does.
I want the update process to run automatically, even when the main app is not open.
Is a Service the best way to go? I've been reading quite a bit about this, I figured a service running all the time for something that is only going to do work once a day seems a little overkill.
However I notice google run service for friendlocation and google+ services continuously on my nexus.
I've look into starting my service via the AlarmManager so its only started when required.
Some posts also suggest using the Handler class, I don't think this will work.
Just looking for the best practice here.
I figured a service running all the time for something that is only going to do work once a day seems a little overkill.
Absolutely.
I've look into starting my service via the AlarmManager so its only started when required.
This is the correct answer.
If you only want your code to be invoked if the device is on, implement an IntentService, do your work in its onHandleIntent(), and have AlarmManager start up the service on your desired schedule.
If you want your code to force the phone to wake up, you can do that, but you will need to use a _WAKEUP-style alarm, and you will probably want to look at my WakefulIntentService, designed to handle this pattern.