【问题标题】:Best way to call a function at specific timestamp [duplicate]在特定时间戳调用函数的最佳方法[重复]
【发布时间】:2016-08-06 22:34:03
【问题描述】:

我想在系统时间戳达到特定时间时调用一个函数。 有什么比 CountDownTimer 更好的吗? 应该在服务上调用它,因为我希望它在应用关闭时仍然运行。

非常感谢。

【问题讨论】:

  • 您可以尝试使用警报管理器,通过它您可以设置特定的时间戳单次或重复出现以运行服务。

标签: java android


【解决方案1】:

你必须像这样使用 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
    }
}

【讨论】:

  • 你不想使用 alarmManager.setExact() 吗?
猜你喜欢
  • 2019-01-29
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2020-04-30
  • 2014-03-24
  • 1970-01-01
  • 2011-04-22
  • 2017-10-24
相关资源
最近更新 更多