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.
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
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)
.
精彩评论