Parag Thuse
Parag Thuse

Reputation: 89

Android Dev: TimerTask and phone sleep weirdness maybe?

i have coded my 2nd android application that switches audio profiles based on a certain schedule (date and time only as of now)....the code is working without any issues if i run the code using the emulator via eclipse...however i recently exported the apk and installed it on my At&t Samsung Galaxy S2 and added the same profile schedule as the emulator, but for some odd reason the timertask is not executing after the 1st time...

For Example: Here is the Profile Schedule from my phone as well as the emulator:

8AM - 5:30PM -- Work

5:30PM - 10PM -- Home

10PM - 8AM -- Sleep

once the above is scheduled and i press the activate button on the main activity..a background service runs switching from one profile to the next until it is de-activated...

the only difference i have noticed between the emulator and my phone is that, the emulator screen never shuts off...so im guessing that the emulator doesnt ever go on sleep? whereas, my phone's screen turns off after about 30 seconds of inactivity, in addition to the lock screen...furthermore, i turned on USB debugging on the phone and plugged it directly into the computer and from what it seemed like, the code was executing, switching one profile to the next, on my phone without any issues...(Note that, when i was doing this testing, i used smaller time intervals in the profile schedules)...Additional details: i have also added startForeground() in my service code and ensured that the service is not getting terminated...

does anyone have any idea on what im missing, or what i can do to get around this bizarre problem?...i did do some research before posting this, and found out few posts that recommended using: Android's PowerManager...

Thanks for your input

Upvotes: 0

Views: 1446

Answers (1)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52956

Nothing weird about this: if the phone is asleep, the CPU is off and you cannot execute code. Don't use TimerTask on Android, use AlarmManager to schedule recurring tasks. It's implemented in the kernel and can wake up the phone if necessary (that might have a negative impact on battery life, so use with caution). Also look into WakeLock's.

http://developer.android.com/reference/android/app/AlarmManager.html

Upvotes: 3

Related Questions