ofirbt
ofirbt

Reputation: 1896

Executing a function at certain hour

I want to execute some function at specific hour picked by TimePicker.

I can use Handler like this:

Handler myHandler = new DoSomething();
Message m = new Message();
myHandler.sendMessageDelayed(m, delay);

class DoSomething extends Handler {
    @Override
    public void handleMessage(Message msg) {
      MyObject o = (MyObject) msg.obj;
      //do something here
    }
}

And load the "delay" param with: picked_wanted_hour - current_hour OR check for the current time at some interval and invoke the function when the time comes.

But, is there any handler-like object that can take a specific time and invoke the operation at that time?

Thanks in advance.

Upvotes: 0

Views: 1398

Answers (2)

darune
darune

Reputation: 959

You can use AlarmManager service :

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

A bref sample:

Intent intent = new Intent(this,<Activity.class/ or type of broadcast receiver>);
PendingIntent pi = PendingIntent.get(...)
AlarmManager am = getSystemService(Context.ALARM_SERVICE);
int delay = 1000; // 1 second
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pi);

more infos on PendingIntent http://developer.android.com/reference/android/app/PendingIntent.html

Upvotes: 2

ernazm
ernazm

Reputation: 9258

Why don't you use handler itself? Just pass timePickerTime - currentTime as a delay.
There's also Timer with method schedule(TimerTask task, Date when).

Upvotes: 1

Related Questions