David Silva Smith
David Silva Smith

Reputation: 11716

How do I use Android's Handler.PostDelayed to make an event happen at a specified time?

I want to have my application execute code at a point in the future.

I want to do:

    Date now = new Date();

    for (Date beep : scheduledBeeps) {
        if (beep.after(now))
        {
            Logger.i("adding beep");
            m_beepTimer.postAtTime(beepNow, beep.getTime());
        }
    }

In the log I can see 4 beeps added, however they never fire. I'm assuming it has something to do with uptimeMillis, but I'm not sure what to do.

Upvotes: 0

Views: 376

Answers (2)

nandeesh
nandeesh

Reputation: 24820

You will have to get the difference between now and beep.gettime() and pass it to postattime function. Since uptime is used as base, it may not be accurate if the phone goes to deep sleep.

beep.gettime - now + SystemCLock.uptimeMillis()

should be passed to postattime function

You are currently passing a very large number equivalent to current milliseconds from jan 1 1970.

Upvotes: 1

Matt Harris
Matt Harris

Reputation: 3544

You could use the Calendar class to set a certain point in time.

Calendar beepTime = Calendar.getInstance();

beepTime.set(Calendar.DAY_OF_MONTH, 2);
beepTIme.set(Calendar.HOUR_OF_DAY, 01);
beepTime.set(Calendar.MINUTE, 55);
beepTime.set(Calendar.SECOND, 00);

getInstance will set it to the current time, and you can change any variable you like, such as the ones above. For example this would create a time at 1:55 on the 2nd of the current month. You would then set this to be the time to go off with

beepTime.getTimeInMillis()

just pop that into your postAtTime method

Edit: Also I don't know enough about your problem to say for sure, but it may be better to use AlarmManager. I know that that still works even if the program is not running, whereas I don't think PostDelayed does. Feel free to correct me if I'm wrong!

Upvotes: 0

Related Questions