如何在 Android 中设置持久/定期计划?

发布于 2024-10-04 10:03:10 字数 137 浏览 0 评论 0原文

如何在每个指定时间(例如每天凌晨 5 点)执行一个操作(可能是一个 Intent)?它必须在设备重新启动后保留,类似于 cron 的工作原理。

我不确定是否可以使用 AlarmManager 来实现此目的,或者可以吗?

How can I execute an action (maybe an Intent) on every specified time (e.g. Every day on 5AM)? It has to stay after device reboots, similar to how cron works.

I am not sure if I can use AlarmManager for this, or can I?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新雨望断虹 2024-10-11 10:03:10

如果您希望它在设备重新启动后保留,则必须在设备重新启动后安排警报。

您需要在 AndroidManifest.xml 中拥有 RECEIVE_BOOT_COMPLETED 权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

还需要 BroadcastReceiver 来捕获意图 ACTION_BOOT_COMPLETED

<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

最后,重写 BroadcastReceiver 中的 onReceive 方法。

public class BootcompletedReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
     //set alarm
  }
}

编辑:查看 setRepeating 方法来安排“Android cron”。

If you want it to stay after the device reboots, you have to schedule the alarm after the device reboots.

You will need to have the RECEIVE_BOOT_COMPLETED permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

A BroadcastReceiver is needed as well to capture the intent ACTION_BOOT_COMPLETED

<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Lastly, override the onReceive method in your BroadcastReceiver.

public class BootcompletedReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
     //set alarm
  }
}

Edit: Look at the setRepeating method of AlarmManager to schedule the 'Android cron'.

提笔书几行 2024-10-11 10:03:10

使用 BuzzBox SDK,您可以在应用程序中安排 cron 作业,执行以下操作:

SchedulerManager.getInstance()
.saveTask(context, "0 8-19 * * 1,2,3,4,5", YourTask.class);

其中“0 8-19 * * 1,2,3,4,5”是一个 cron 字符串,它将每小时运行一次任务,从上午 8 点到晚上 7 点,周一至周五。
你的任务可以是任何你想要的,你只需要实现一个 doWork 方法。该库将负责重新安排重新启动、获取唤醒锁以及重试错误。

有关 BuzzBox SDK 的更多信息请点击此处...

Using the BuzzBox SDK you can schedule a cron job in your App doing:

SchedulerManager.getInstance()
.saveTask(context, "0 8-19 * * 1,2,3,4,5", YourTask.class);

Where "0 8-19 * * 1,2,3,4,5" is a cron string that will run your Task once an hour, from 8am to 7pm, mon to fri.
You Task can be whatever you want, you just need to implement a doWork method. The library will take care of rescheduling on reboot, of acquiring the wake lock and on retrying on errors.

More info about the BuzzBox SDK here...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文