I have created an Android service which basically does the following:
schedule a task, using the ScheduledThreadPoolExecutor.schedule() method
when the schedule time is reached, the task is executed and a new schedule is started
Thus, the service continuously has a timer in place (except during execution of the task); sometimes 2 (independent) timers are in place, depending on the result of the task. The service should be running all the time and executes different tasks from time to time.
All seems to work ok (at least when running with DDMS), but after a while (something like an hour without connecting the device via DDMS) the timer tasks are not executed anymore. The only way to get it working again is either stopping and starting the service again or by connecting the device with DDMS (using Eclipse); waking up the device only does not trigger this.
It looks like, Android sets the service in a kind of sleep mode (service is still running when looking at the Active Services on the device).
My question is: how do I prevent this behavior and keep the service working all the time?
I did some research and I found something which theoretically could give a solution, by acquiring a (PARTIAL_WAKE_LOCK) WakeLock in the service, but as far as I understand, using this solution, I have to acquire the lock at the onStartService() method and release it at onDestroy(), meaning that I keep the lock during the lifetime of the service (which is forever); I suspect a battery drainage using this method.
Is there another way to accomplish the same?
I have solved the problem, thanks to the replies above.
I switched from the ScheduledPoolThreaExecutor() to the AlarmManager. Together with the RTC_WAKEUP type all triggers are handled now.
I did not use the IntentService, because my service has to do things in parallel based on alarms (and IntentService implements a queued solution). The original service, which was staying alive all the time in the original implementation, is now only created whenever an alarm is triggered.
I also have the impression (but that is only a gut feeling, not based on real measurements, that this new implementation (where the service is created when needed and is not alive all the time (waiting on timer evens), is even better for battery life of the device.
How often to you need to execute, and what do you mean by running all the time? I guess that you don't mean be executing all the time?
I have a service that does this, and it works quite well:
It schedules an alarm with the alarm manager. Acquires a wakelock when the alarm is triggered, performs some work, and then schedules a new alarm before releasing the wake lock.
Use IntentService for your service implementation and register pending intents with AlarmManager to trigger those intents on the time basis you need.
I have used wake locks in an app before and I did not need to release them in the onDestroy(),
I literally had the following and it worked perfectly:
onClockListener{
acquire wakelock
method call
}
otherOnClickListener{
release wakelock
other method call
}
Not sure if it will help much but it definitely wont help if I don't post anything :)
Related
I am building a fitness app which continually logs activity on the device. I need to log quite often, but I also don't want to unnecessarily drain the battery of my users which is why I am thinking about batching network calls together and transmitting them all at once as soon as the radio is active, the device is connected to a WiFi or it is charging.
I am using a filesystem based approach to implement that. I persist the data first to a File - eventually I might use Tape from Square to do that - but here is where I encounter the first issues.
I am continually writing new log data to the File, but I also need to periodically send all the logged data to my backend. When that happens I delete the contents of the File. The problem now is how can I prevent both of those operations from happening at the same time? Of course it will cause problems if I try to write log data to the File at the same time as some other process is reading from the File and trying to delete its contents.
I am thinking about using an IntentService essentially act as a queue for all those operations. And since - at least I have read as much - an IntentServices handles Intents sequentially in single worker Thread it shouldn't be possible for two of those operations to happen at the same time, right?
Currently I want to schedule a PeriodicTask with the GcmNetworkManager which would take care of sending the data to the server. Is there any better way to do all this?
1) You are overthinking this whole thing!
Your approach is way more complicated than it has to be! And for some reason none of the other answers point this out, but GcmNetworkManager already does everything you are trying to implement! You don't need to implement anything yourself.
2) Optimal way to implement what you are trying to do.
You don't seem to be aware that GcmNetworkManager already batches calls in the most battery efficient way with automatic retries etc and it also persists the tasks across device boots and can ensure their execution as soon as is battery efficient and required by your app.
Just whenever you have data to save schedule a OneOffTask like this:
final OneoffTask task = new OneoffTask.Builder()
// The Service which executes the task.
.setService(MyTaskService.class)
// A tag which identifies the task
.setTag(TASK_TAG)
// Sets a time frame for the execution of this task in seconds.
// This specifically means that the task can either be
// executed right now, or must have executed at the lastest in one hour.
.setExecutionWindow(0L, 3600L)
// Task is persisted on the disk, even across boots
.setPersisted(true)
// Unmetered connection required for task
.setRequiredNetwork(Task.NETWORK_STATE_UNMETERED)
// Attach data to the task in the form of a Bundle
.setExtras(dataBundle)
// If you set this to true and this task already exists
// (just depends on the tag set above) then the old task
// will be overwritten with this one.
.setUpdateCurrent(true)
// Sets if this task should only be executed when the device is charging
.setRequiresCharging(false)
.build();
mGcmNetworkManager.schedule(task);
This will do everything you want:
The Task will be persisted on the disk
The Task will be executed in a batched and battery efficient way, preferably over Wifi
You will have configurable automatic retries with a battery efficient backoff pattern
The Task will be executed within a time window you can specify.
I suggest for starters you read this to learn more about the GcmNetworkManager.
So to summarize:
All you really need to do is implement your network calls in a Service extending GcmTaskService and later whenever you need to perform such a network call you schedule a OneOffTask and everything else will be taken care of for you!
Of course you don't need to call each and every setter of the OneOffTask.Builder like I do above - I just did that to show you all the options you have. In most cases scheduling a task would just look like this:
mGcmNetworkManager.schedule(new OneoffTask.Builder()
.setService(MyTaskService.class)
.setTag(TASK_TAG)
.setExecutionWindow(0L, 300L)
.setPersisted(true)
.setExtras(bundle)
.build());
And if you put that in a helper method or even better create factory methods for all the different tasks you need to do than everything you were trying to do should just boil down to a few lines of code!
And by the way: Yes, an IntentService handles every Intent one after another sequentially in a single worker Thread. You can look at the relevant implementation here. It's actually very simple and quite straight forward.
All UI and Service methods are by default invoked on the same main thread. Unless you explicitly create threads or use AsyncTask there is no concurrency in an Android application per se.
This means that all intents, alarms, broad-casts are by default handled on the main thread.
Also note that doing I/O and/or network requests may be forbidden on the main thread (depending on Android version, see e.g. How to fix android.os.NetworkOnMainThreadException?).
Using AsyncTask or creating your own threads will bring you to concurrency problems but they are the same as with any multi-threaded programming, there is nothing special to Android there.
One more point to consider when doing concurrency is that background threads need to hold a WakeLock or the CPU may go to sleep.
Just some idea.
You may try to make use of serial executor for your file, therefore, only one thread can be execute at a time.
http://developer.android.com/reference/android/os/AsyncTask.html#SERIAL_EXECUTOR
I have a service that runs periodically using a timer to invoke itself, but should not run when the screen is off. When the screen on event is fired, the service should run, but only if it's past when the timer would have fired.
Right now I still run the timer continually, but have the service do nothing if the screen is off. I can also run the service via a broadcast receiver when the screen turns on - but this runs the service every time the screen is turned on, instead of only when it's past when the timer should have run. Recording this state in the service doesn't seem to work as Android will kill the JVM for the app in between executions.
What would be the cleanest/correct way to implement this type of behavior?
So there are a couple of intents that you can listen for, Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON. However, these don't work as manifest receivers, they need to be explicitly registered.
See this answer: https://stackoverflow.com/a/9478013/1306452
In all scenarios, it's going to involve a long running service in order to listen for those events.
One thing to keep in mind is that these intents only listen for when the device becomes non-interactive and vice versa, not specifically when the screen goes off (see the description on the Intents).
The best way for you to achieve this behaviour would be to listen for when these intents with a long lived service, started with START_STICKY to help guarantee that the service is running. The service can register a receiver for the SCREEN_ON and OFF events, and when it gets these events either do nothing if the timer has not elapsed, or continue if it has.
This won't be nice on your battery life, and what ever you are doing it doesn't sound like it's going to be a pleasent user experience. You might also want to step back and see if there's another way around this obstacle (my 2 cents).
Im fairly new to Android and have encountered a problem, which i would like to understand. The problem is that the java.util.concurrent.ScheduledExecutorService doesn't seem to issue its tasks while the display of my smartphone is off. I was using a java.util.Timer before which didn't have this issue, but was transitioning to ScheduledExecutorService because of the need to wait for the end of the task execution after stoping the Timer. The Timer is used in a Service running in the background.
Note: Using AlarmManager isn't an option, because i want to understand the problem with ScheduleExecutorService or else will use Timer again (synchronizing the shutdown).
Here is how the task is scheduled:
mScheduler = Executors.newSingleThreadScheduledExecutor();
mScheduler.scheduleAtFixedRate(mTask, 1, 1, TimeUnit.SECONDS);
To furher clarify the purpose: I am trying to update a Notification as well as parts of the User Interface periodically, this doesn't need to be done if the device wants to go into "sleep" mode, but i would need to handle this case. I think understanding why ScheduledExecutorService is behavoring the way it does compared to Timer will help me handle it.
UPDATE:
As recommended by Chris Stratton, i'm using a BroadcastReceiver to receive the Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF Intents to pause/resume the ScheduledExecutorService, which works like a charm. However there seems to be another issue with the ScheduledExecutorService while having a phone call, the execution doesn't stop but seems to be throttled somehow. This is only the case if the screen is turned off due to the proximity sensor (no intents are received in this case either)...
When the screen is off, if no other applications are holding WakeLock, the CPU suspends.
You should use a PARTIAL WakeLock whenever you need something done while screen is off.
And make sure you release it as soon as you've done all the ackground job.
I need my android application to stay alive for a short specific duration.
I have a long series of updates, during which I keep the screen alive with wake looks. After that is done, there is an dialog informing of the success. Before this one is posted however I've released the wake look. Here I want the application to have a wakelock for 30s and then release it even if the user dos not click ok on the dialog. This is because I dont want to drain the mobile.
Is there an easy way to do this? That is, once I've reached a certain stage in my code I want to have a wakelock for a short duration?
For any long running tasks you should use a service, and for your purpose a ForegroundService.
This comes with the requirement to have a notification visible while your service is running. You can then post a different notification once the process is complete.
This will make your processing resilient to the user stand-by'ing the phone, rotating the phone or going to another app, all of which would interrupt processing if originating in an activity.
http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)
For ease of use, I usually override IntentService which has the least amount of boiler code required to get going.
I'm trying to write a simple app that should mute my mobile phone for a given time. It's my first Android app, but after many hours of reading I think it is nearly completed. But it still has one problem that I can not fix.
I'm using a activity to display the GUI. It has Buttons to set the start and end time, and everything else needed. When the user has entered all the parameters, they are passed to a service. This service uses a handler object, to register 2 callbacks (with Handler.postDelayed). One for start Mute and one for End Mute (in SetMuteIntervall).
The first tests seemed to work, but if I try to mute it for like 30 minutes, it never unmutes. I think it has something to do with the fact, that the mobilephone is or was in standby mode. I also tried to use Handler.postAt() but that didn't work either (and time relative to uptime was somewhat confusing).
So, what should I do to guarantee, that my callbacks are called, regardless whether the phone is in standby or not?
Here's the source of my program:
http://pastebin.com/XAgCeAq9
http://pastebin.com/33nepFV5
Try to use AlarmManager for planning some actions in future. AlarmManager is not standby-mode-dependend and will fire even if device is sleeping.
Your thread are actually stopped then the phone is in stand by mode. If you still want to use thread you can use WakeLock to prevent CPU from going to stand by mode (but still to switch screen off) but this is not the best way in your case.