Currently, I am trying to run a piece of code at a specific time. After some research, I think the correct way to go is to make usage of the AlarmManger
. The code s
I think this is due to the fact, that the Power Manager causes Problems with the App Actvivity.
Try using the Power Manager
PARTIAL_WAKE_LOCK
added in API level 1 int PARTIAL_WAKE_LOCK Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.
If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all partial wake locks have been released.
Constant Value: 1 (0x00000001)
This is just an assumption, if it still doesnt work, could you post some Logs or more code snippets of the activity :)
Example:
//Initialize the Power Manager
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//Create a PARTIAL_WAKE_LOCK
//This will keep the cpu running in the Background, so that the function will be called on the desired Time
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
//Check if the WackLock is held (may throw erro if you try to acquire twice)
//TRUE --> Do nothing, all good
//FALSE --> Acquire the WakeLock
if(!wl.isHeld()){
wl.acquire();
}
//*****
//You code for the repeating task goes Here
//*****
//If the Repeating task is not active, release the Lock
//Check if the WackLock is held (may throw error if you try to release a none acquired Lock)
//TRUE --> Release Lock
//FALSE --> Do nothing, all good
if(wl.isHeld()){
wl.release();
}
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time.
Inexact scheduling means the time between any two successive firings of the alarm may vary. Thats what happening in your case i guess.To overcome the exact time issue i think you should use one shot alarm.But in this case you need to reschedule it for next day. and so on. You can get a very clear understanding from the Documentation setrepeating , setInexactRepeating.
EDIT:- TO optimizing DOZE mode
In Case you are Using setAndAllowWhileIdle()
or setExactAndAllowWhileIdle()
,
Then you must read This Document which says :-
Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app.