NicePiao
NicePiao

Reputation: 41

android how to deal with android timer when phone goes to sleep

Our Application has a service which starts a timer to schedule a task every 4 hours.
But the phone often goes to sleep when the screen is off.
I don't expect the task to run when the phone is sleeping.
But I want that it can be run immediately if the phone has slept longer than 4 hours.

TimerTask task = new TimerTask() 
{

            @Override
    public void run() {
                          //do something
        }
    };

new Timer().schedule(task, 0,  4*60*60*1000);//period=4 hours;

I have done some tests that show if then phone has slept for more than 4 hours and when it wakes up, the timer's period didn't add the past 5 sleep hours and it can't run the task immediately.
Its period time just calculates the phone's wake time.
I have studied Timer.java, and know the timer's delay mechanism is to use thread wait(), that is the reason.
How to make a cyclic time task that contains the phone sleep time?
I think there is no need to use an AlarmManager, because the task doesn't need to run when the phone is sleeping.
Thanks in advance.

Upvotes: 4

Views: 1921

Answers (1)

Ryan S
Ryan S

Reputation: 4567

Instead of using Timer, you need to use AlarmManager without the wakeup option set. If you do this the alarm will trigger the next time you wake up the phone after the 4 hours..

Check out this tutorial: http://www.techrepublic.com/blog/software-engineer/use-androids-alarmmanager-to-schedule-an-event/

Upvotes: 1

Related Questions