Executing a function at certain hour

我与影子孤独终老i 提交于 2020-01-16 19:06:12

问题


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.


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/6074351/executing-a-function-at-certain-hour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!