如果互联网连接到设备,如何每小时调用一次网络服务

How call webservice in every hour if internet connected to device

我想在连接互联网时在后台调用网络服务。如果已连接,我想每隔一小时打电话一次,如果互联网关闭,则停止服务。我怎么能够?它需要适用于从 16 到 27 的所有版本。

android 中有广播,如果网络状态发生变化会通知您。在那里你可以注册一个小时的警报管理器并检查互联网是否连接然后调用网络服务。

如果广播通知您网络断开,那么您可以取消警报管理器。

这里是监听网络状态变化的文档:

https://developer.android.com/training/monitoring-device-state/connectivity-monitoring

这是关于在 android 中使用警报管理器的好教程 https://en.proft.me/2017/05/7/scheduling-operations-alarmmanager-android/

还 google 介绍了 workManager,它以非常简单的方式为您完成这项工作

The WorkManager API makes it easy to specify deferrable, asynchronous tasks and when they should run. These APIs let you create a task and hand it off to WorkManager to run immediately or at an appropriate time. For example, an app might need to download new resources from the network from time to time. Using these classes, you can set up a task, choose appropriate circumstances for it to run (like "only while device is charging and online"), and hand it off to WorkManager to run when the conditions are met. The task is still guaranteed to run, even if your app is force-quit or the device is rebooted.

这里是 link 文档:

https://developer.android.com/topic/libraries/architecture/workmanager