【问题标题】:Android: Get system time and schedule a taskAndroid:获取系统时间并安排任务
【发布时间】:2014-04-16 18:23:51
【问题描述】:

我一直在试图弄清楚如何在 android 中获取当前时间,并且我想知道如何在时钟到达某个时间时运行一段代码。最终我想要做的是时钟是晚上 9:30。做某事或运行一段代码。我以前从未在 android 或 java 上处理过时间。

【问题讨论】:

  • 您的应用程序将作为服务运行还是您需要在 @ 9:30 启动?

标签: java android time alarmmanager


【解决方案1】:

使用AlarmManager 时需要考虑一些事项,尤其是当您的设备处于睡眠状态时(获取锁,并一直保存到您的任务完成)。我建议你阅读that

【讨论】:

    【解决方案2】:

    您可以通过多种方式获取 Android 中的当前时间,例如

    Date currentDate = new Date(System.currentTimeMillis());
    

    关于在特定时间运行的代码,请查看AlarmManager,它允许您为您的应用程序安排运行。

    另外,请查看Alarm Manager Example

    【讨论】:

      【解决方案3】:

      试试这个:

      获取当前系统时间如下:

      long currentTime = System.currentTimeMillis();
      

      并设置未来时间的任务如下:

      Calendar cal = Calendar.getInstance();
      cal.add(Calendar.SECOND, 10);
      Intent serviceIntent = new Intent(this, GPSTrackerService.class);
      PendingIntent pintent = PendingIntent.getService(this, 0, serviceIntent, 0);
      AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      //every 2 min
      alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),timeSlice, pintent);
      

      更多描述请参考以下链接:

      How to set an alarm to fire properly at fixed time?

      【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多