Running an Activity a certain interval before going to sleep - android

I am currently working on customizing an Android system and would like that, a few minutes before going to sleep, a given Activity is run, with the same premises as the sleep function (e.g. if the user performs any action, its timer gets reset).
For instance, let's say that we set its timer to 5 minutes and the device is set to go to sleep after 10 minutes. This means that, as long as there is no user input (or wakelocks acquired etc.), after 5 minutes my Activity is started, and after another 5 minutes the device enters sleep mode (think of it similar to a screensaver).
My initial searches have lead me to the PowerManagerService class, where the ACTION_SCREEN_OFF is broadcast, but the general idea of the code there has so far eluded me.
Any help would be appreciated.
Thank you.

This is not possible, sorry. You have no way of determining system-wide inactivity up until the ACTION_SCREEN_OFF broadcast is sent.

Maybe you can use Wakelock to delay the sleep.
implement a broadcastreceive , filter the ACTION_SCREEN_OFF
when receiving the ACTION_SCREEN_OFF , lock the PARTIAL_WAKE_LOCK
do what you want....
when you finish all the job, release Wakelock. then system go to sleep.

Related

Does need Broadcast receiver to WakeLock

I have two questions.
I want fire a Broadcast receiver using AlarmManager and show a notification in onReceive method. Should I use from WakeLoke for this?
What is different between setAlarmClock() and setExactAndAllowWhileIdle() ?
I use (as you wrote) the onReceive method to start a newWakeLock and it works fine for me.
The difference lies in the behavior in doze mode (Doze Mode: https://developer.android.com/training/monitoring-device-state/doze-standby).
I do not know your exact problem, but I worked very hard to develop an app which contains few timers and every timer should make a notification at the exact time even the screen is locked and the device is in the doze mode. My solution is to fire an Broadcast over an AlarmManager with the setExact(...) method.
Answer your question in reverse order
.2. setExactWhileIdle guarantees that if the system is not sleeping and not in doze, the alarm will go off within 1 minute of the given time. if the system is in doze mode, the alarm will go off within 15 minutes of the given time. In practice, if the system is not in doze mode or low on battery, the alarm will go off on time. On the other hand, setAlarmClock is the closest one can get to a guarentee that the system will deliver the alarm at a specific time; this does come at a relatively large drain on battery. So, if your goal is to implement highly time sensitive notifications such as an alarm clock, then use setAlarmClock. Otherwise try to avoid it.
.1. according to the documentation, upon an alarm being dispatched from setExactAndAllowWhildIdle or setAlarmClock:
the app will also be added to the system's temporary power exemption list for approximately 10 seconds to allow that application to acquire further wake locks in which to complete its work.
My suggestion is that if all you are doing is posting a notification, then a wake lock is not necessary. Otherwise, if you are doing longer running work, use a wake lock
Obligatory Disclaimer: battery drain is a real thing. please don't make an app that drains the battery. do everything in your power to design your app not to disturb the systems power optimization. All exact alarms and especially setAlarmClock disrupt the systems attempts to optimize battery. If its necessary, then its necessary. Otherwise, do not do it.

Listen to app wake up event / schedule a wake up event

I'm trying to schedule event. For example, i'd like for something to happen 1 hour from now. For this i used handler postdelayed. Unfortunetly, this doesn't work as expected. I guess the reason is that android puts my app to some kind of sleep state, so the timer freezes at some point, and keeps counting from the point stopped when the device is back to use. This causes the event to occur at unknown time, greater than the time expected.
Now, i have two ways to solve this and i'd like to know how to implement each one:
Schedule to wake the device at a specific time and then excecute the event. I don't know how to schedule a wake up (and do it efficently).
Excecute the event as soon as my app wakes, if the time of execution has passed (i can use date and time to verify if the time passed). What i miss here is how to listen to wake up event.
And for my general knowledge about android sleep policy: Does android put services and activities to sleep automatically? how, if so, any messaging app keeps listening to new messages?
Thanks in advance for any help :)
You have to use Alarms,
Alarms give you a way to perform time-based operations outside the lifetime of your application.
android has 4 types of Alarms :
ELAPSED_REALTIME—Fires: the pending intent based on the amount of time since the device was booted, but doesn't wake up the device. The elapsed time includes any time during which the device was asleep.
ELAPSED_REALTIME_WAKEUP—Wakes: up the device and fires the pending intent after the specified length of time has elapsed since device boot.
RTC—Fires: the pending intent at the specified time but does not wake up the device.
RTC_WAKEUP—Wakes: up the device to fire the pending intent at the specified time.
Read this pages Alarms

Acquire wake lock, release it and acquire it again while the phone is sleeping

I think this is pretty much the standard case already described in other SO question but I still need a clarification on this matter:
So I have an Android app with an Actvity and a Service. The Activity is not of interest but the Service. The Service has to send some message to a remote server every minute. From what I understand, I need to use WakeLocks to keep the CPU running while allowing the screen to go off (so that I can fix the problem where the service stops when the screen is powered off). So far so good.
My question is: can I acquire the lock, send the message to the server, release the lock AND acquire it again after one minute so that during this one minute pause the CPU is sleeping, too. With the ultimate goal to save the battery. I fear the answer is "no" because once you let the CPU to sleep, you cannot wake it up unless from a lower level (OS and not app).
Best regards
The response is simple: no. What you can do in this case is set a PendingIntent and use the Android Alarm manager to be woken up every minute.
The alarm manager is the way to go - but you also need to delegate from the alarm receiver to a WakefulIntentService to do the work (as the receiver will ANR after 5 seconds). See PowerManager.PARTIAL_WAKE_LOCK android for links.

Will a Handler postDelayed not being fired when CPU sleeps?

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.

Do tasks when device wakes up

I'm have a widget that is being updated from a service. When the user then turn off the screen, the service stops and won't start to update the widget again when the user wake up the device. So on to my question, is there some way to "restart" the service when the user wake up the device? I know I can keep the service keep going when the screen is locked, but I think it would drain to much battery then... I have google'd alot but haven't found anything...
Thanks in advance!
EDIT: Okey, this is strange! Now somehow it does that automatically, so it's working now! Thanks anyway!
EDIT 2: Or, now I don't really think it's the screen lock that stops the service, cause it just sometimes stops randomly without crashdialog when I use the phone... Anyone know how I should do to fix that?
For a widget it usually doesn't make sense to keep a service running all the time, you usually update the widget periodically.
The easiest way to do this and to be battery efficient is to schedule an intent using AlarmManager and setAlarmInexactRepeating:
Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour. These alarms are more power-efficient than the strict recurrences supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' phase to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.
The intent should trigger a BroadcastReceiver which in turn should trigger your service to update the widget. Using IntentService is usually a good choice for that.
If you need more control over the intent scheduling, you can also set the alarms yourself in when the service is finished with updating the widget, and supply RTC or ELAPSED_REALTIME as the type of alarms. Both types won't wake up the device if it's sleeping. If the device is not sleeping (but locked) you'll effectively piggy back on other events that woke the device.
If you really need to update as soon as the device is unlocked, the ACTION_USER_PRESENT broadcast might be what you need, but I'd still recommend to implement that as an addition to scheduling a periodic update.
Yes this is Possible!
When the user turn off the screen You Have to handle BroadCast Receiver (http://developer.android.com/reference/android/content/BroadcastReceiver.html)
That handle to Stop service & the service stops and stop to update the widget,
when the user wake up the device you have to Receive Broadcast start to update the widget.
I think it would be The best idea to save more battery.
For More information Please Refer this Link

Categories

Resources