【发布时间】:2016-08-06 22:34:03
【问题描述】:
我想在系统时间戳达到特定时间时调用一个函数。 有什么比 CountDownTimer 更好的吗? 应该在服务上调用它,因为我希望它在应用关闭时仍然运行。
非常感谢。
【问题讨论】:
-
您可以尝试使用警报管理器,通过它您可以设置特定的时间戳单次或重复出现以运行服务。
我想在系统时间戳达到特定时间时调用一个函数。 有什么比 CountDownTimer 更好的吗? 应该在服务上调用它,因为我希望它在应用关闭时仍然运行。
非常感谢。
【问题讨论】:
你必须像这样使用 BroadcastReceiver 和 AlarmManager。
//Create alarm manager
AlarmManager malarmMngr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent = new Intent(this, yourBroadcastReceiver.class);
PendingIntent mPendInt = PendingIntent.getBroadcast(this, 0, intent, 0);
//set your time stamp (for once in future)
malarmMngr .set(AlarmManager.RTC_WAKEUP, yourtimestamp, mPendInt);
现在创建你的BroadcastReceiver 类来调用函数。
public class yourBroadcastReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// This method is called when this BroadcastReceiver receives an Intent broadcast.
// Call your function here
}
}
【讨论】: