I want to run a thread to do some work in the background (from a service that acquired a wakelock). after my thread finish work then it will stop the service.
My concerns are :
1- Do i need to require a wakelock in the thread that was started in the service?
2- Can the system kill my thread while leaving my service running?
3- if 2 is the case how could i stop my service (can i give the service a timeout time that it will die after it)
WakeLocks are, as I understand applied to the Android component (e.g. service, activity, etc.) and all its associated threads. So you would not have to aquire a new wakelock in your thread. You could prove this by passing the aquired lock and calling isHeld from the started thread.
You should consider a partial wakelock, this will concern only keeping the CPU running, regardless of the screen or keyboard activity. Since this is a service I assume you don't care whether the screen stays on.
Note that it states here: If you hold a partial wakelock, the CPU will continue to run, irrespective of any timers and even after the user presses the power button. In all other wakelocks, the CPU will run, but the user can still put the device to sleep using the power button.
Edit: Also, even though you can do it the way you suggested, it might be better to only aquire and release the wakelock in the child thread for battery consumption purposes. And if you are needing to use WiFi for this work a WiFiLock may also be required.
Related
If I have an IntentService that simply updates the SharedPreference, is a (partial) WakeLock needed?
I understand that a WakeLock keeps the CPU awake, but when is it needed?
If you need to keep the CPU running in order to complete some work before the device goes to sleep, you can use a PowerManager system service feature called wake locks. Wake locks allow your application to control the power state of the host device.
Creating and holding wake locks can have a dramatic impact on the host device's battery life. Thus you should use wake locks only when strictly necessary and hold them for as short a time as possible. For example, you should never need to use a wake lock in an activity.
One legitimate case for using a wake lock might be a background service that needs to grab a wake lock to keep the CPU running to do work while the screen is off. Again, though, this practice should be minimized because of its impact on battery life.
Unfortunately, some poorly-coded, malicious, or simply buggy apps might create an abnormal amount of undesirable wakelocks. Other apps require constant Internet access in order to operate in a normal fashion - Facebook and Messenger are probably the most popular representatives. They persistently request information from the web (the so-called "polling" for new events), which is causing subsequent wakelocks.
In other cases, an update to a given app can also cause certain issues, which usually result in partial wakelocks. The latter keep your CPU constantly humming in the background, sometimes without your knowledge, and prevent your device from "going to sleep". That's a pretty substantial prerequisite for anomalous battery drain. Thus, it is advisable to regularly monitor the wakelocks on your device and see which of your apps go harsh on our system's resources.
Read more at:
What-are-wakelocks-how-they-affect-the-battery-life-of-your-Android-device-and-how-to-Greenify
Reference: https://developer.android.com/training/scheduling/wakelock.html
It is needed when you don't want CPU to sleep when user locks the screen for example.
If you have an IntentService without acquired WakeLock it will pause after a while if user locks the screen and it will continue its work when user wakes a device. With WakeLock acquired your service will work even if the screen is locked.
As #My God mentioned, it impacts on battery life a lot, so, use it only when you really need to finish some operation and you cannot wait till user wakes a device.
I have a single started service in my application which keeps my application alive.
I am downloading the data in a thread in my application(may take from 1 minute from 30 minute).
I want my application not to go in sleep state. I dont want to use the PARTIAL_WAKELOCK mechanism to keep the battery life long.
Here, The intention of having some PARTIAL_WAKELOCK like functionality not because of the service,
I want it just for few threads(tasks).
Can AlarmManager help?
I want my application not to go in sleep state.
Then use a WakeLock.
I dont want to use the PARTIAL_WAKELOCK mechanism to keep the battery life long.
You do not have a choice.
Here, The intention of having some PARTIAL_WAKELOCK like functionality not because of the service, I want it just for few threads(tasks).
A WakeLock does not affect a service. It does not affect a "few threads". It affects the device's CPU. The CPU is what goes to sleep, not your service, and not your threads. If you do not want the CPU to go to sleep, you must use a WakeLock.
I have an activity with some Handlers that are being executed at intervals no more than 5 minutes. The activity is launched from a BroadcastReceiver and may be launched with the screen off waiting for the user to grab the phone and get the user input, when this happens, the activity onPause() is called so for sure CPU is in sleep mode. I have not set the activity to turn screen on because I want to save as much battery as possible.
I've tested it with my phone and works really well, while screen is off all Handlers execute all the code they have to run. If I turn the screen on and off while the activity is open everything works fine.
Now, I've read everywhere that some devices does not work as expected when screen goes off and CPU sleeps, most of the times with accelerometers. Now my question is, do I need to acquire a WakeLock so the CPU does not sleep while my activity is open? I really want to know this because, as I said before, I don't want to 'waste' battery by acquiring an expensive WakeLock.
I would prefer a detailed answer of a person that really knows how this works.
Your goal cannot be stably achieved by your approach. If you use an Handler's postDelayed() method and the CPU goes to deepsleep, the ms counter will stop and will only continue if the CPU wakes up again.
See this for more detail.
So if you want to have some kind of a cron job you will need to use wakelock.
Fortunately there is a Service implementation that does exactly that: Wakeful IntentService
From the doc:
The recommended pattern for Android's equivalent to cron jobs and Windows scheduled tasks is to use AlarmManager. This works well when coupled with an IntentService, as the service will do its work on a background thread and shut down when there is no more work to do. There's one small problem: IntentService does nothing to keep the device awake. If the alarm was a WAKEUP variant, the phone will only stay awake on its own while the BroadcastReceiver handling the alarm is in its onReceive() method. Otherwise, the phone may fall back asleep. WakefulIntentService attempts to combat this by combining the ease of IntentService with a partial WakeLock.
I know android use wake lock to keep cpu running or screen on.
It's obvious that screen wake lock prevents the user active timer from turning off the screen after a period of user inactivity.
But I'm wondering when exactly will the cpu wake lock take effect.
1.If I create a new thread and keep draining cpu in background with out any wake lock, turn off the screen will not stop it. Will it stop and when will it stop?
2.What about a thread scheduled with Timer.schedule()?
3.It leads to another question, if I keep a long socket connection in a service, which is blocked at socket.read(). Do I have to acquire a wake lock to make sure the service will be wakeup when the socket receives any data form remote?
Thanks.
Answers to all your sub-questions
Android sleeps when no wake-lock is active. It does not matter what processes and threads are running it will still sleep. That means if your thread or some other process out there has not activated a wake lock your thread will not execute and hence will not drain any battery. The thread will be made active only when some other process acquires a wakelock.
Same is applicable to the Timer.schedule(). Say you write a Timer that executes every second but without any wake-lock, and say android goes to sleep for 10 seconds. When it wakes p on 11th second it will identify that your timer has expired 10 times it will simply discard the9 instances and execute it only once. If you want very reliable timers you will have to either obtain a wake lock or user AlarmTimer.
Yes.
What i learn from different functionality related to Wake-Lock , Android System will never sleeps, if it sleeps you will not get SMS , Call i.e Android will not run only OS level task when it goes on sleep.
Wake-lock is a mechanism where any application can request system to have the device stay on for him. Application can perform operation on background despite user haven`t move to launch that application.
For 1 & 2 Akshar has explained correctly.
3. As to perform any operations in your application while system is in sleep state(only OS level task are runnning) , you first have to request wake-lock from system and then only application can run its operations. After completing operations you should release the wake lock so that system can move to managing OS level tasks.
I am new to the notion of WakeLock and need your help.
Questions:
I assume WakeLock to be some type of lock which when held by the executing code prevents the device from sleeping. What if the device is already in sleep/standby mode, will the code execute then? Assuming that it would never acquire a WakeLock?
When a long running task(abt 7-8 sec) is done in a background thread(AsyncTask) should I be bothered about holding a WakeLock? Does AsyncTask already acquire it for me?
links to official documentations and writeup on wakelocks are appreciated.
Thanks.
1.If the phone is in full sleep mode, aside from an incoming phone call, you could use an AlarmManager intent to wake the phone up.
From the AlarmManager class documentation:
The Alarm Manager holds a CPU wake
lock as long as the alarm receiver's
onReceive() method is executing. This
guarantees that the phone will not
sleep until you have finished handling
the broadcast. Once onReceive()
returns, the Alarm Manager releases
this wake lock. This means that the
phone will in some cases sleep as soon
as your onReceive() method completes.
If your alarm receiver called
Context.startService(), it is possible
that the phone will sleep before the
requested service is launched. To
prevent this, your BroadcastReceiver
and Service will need to implement a
separate wake lock policy to ensure
that the phone continues running until
the service becomes available.
2.If you're working with an AsyncTask, you will want to publish results on to the UI thread on onPostExecute()
From the AsyncTask documentation:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
3.I suggest you have a read at the official documentation of Power Manager which gives a good introduction to the WakeLock concept.
Typically the only code that would run while the phone is sleeping is a BroadcastReceiver. Actually, the phone wakes up for a second, runs the BroadcastReceiver's code and sleeps again. Since you should never run long code in a BroadcastReceiver (use it to launch a Service instead), you can basically assume that your code is never run while the phone is sleeping. Of course, if you are using a BroadcastReceiver to start a Service, you should usually obtain a WakeLock.
With an AsyncTask initiated by the user, you don't really need to worry about WakeLocks. It is unlikely the phone will sleep while it is running. I'm not sure if they get a WakeLock, but putting my phone to sleep while running a standard AsyncTask doesn't seem to interrupt the it.
As SteD said, check this out: http://developer.android.com/reference/android/os/PowerManager.html
Basically the only time you need to worry about WakeLocks is when you either expect your task to be interrupted by sleeping (as is the case if you set an alarm that wakes the phone up briefly) or if you absolutley cannot have the task interrupted. Otherwise, just make sure that you gracefully handle any interruptions.