在后台检查新数据 [英] Checking for new data in background

查看:27
本文介绍了在后台检查新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论应用是在前台还是后台,检查新数据的推荐方法是什么?我想知道人们通常使用哪些 Android API 来执行此操作.似乎有几种方法可以实现我的目标,我想确保自己走在正确的道路上.

What is the recommended approach for checking for new data regardless if the app is in the foreground or background? I am wondering which Android API people are typically using to do this. There seems to be a few ways to achieve my goal, and I want to make sure I'm on the right path.

我有一些东西放在一起,它使用 AlarmManager.SetInexactRepeating() 来调用一个 IntentService,它在数据库中执行同步和插入/更新数据.这在应用程序处于前台和后台时有效,但如果我强制停止应用程序,那么当 AlarmManager 警报触发时,我会一直看到不幸的是,已停止工作"消息.在这种情况下,我只关心应用在前台或后台运行时是否检查新数据.

I have something put together which uses AlarmManager.SetInexactRepeating() to call an IntentService which does the sync and inserts/updates data in the database. This works while the app is in the foreground and background, but if I force stop the app then I keep seeing "Unfortunately, has stopped working" messages when the AlarmManager alarm would've triggered. In this case, I only care about checking for new data only when the app is running in the foreground or background.

我的第一个想法是检测应用程序何时被强制关闭并停止警报,但这似乎不可能.所以我在这里问,我的方法错了吗?如果是这样,无论手机是在前台还是后台,都使用哪种方法来执行某些周期性任务?我使用的 AlarmManager 解决方案的问题是即使关闭应用程序,警报也会继续触发.

My first thought is to detect when the app is force closed, and stop the alarm, but that does not seem possible. So I am asking here, is my approach wrong? If so, which approach is used to perform some periodic task regardless if the phone is in the foreground or background? The problem with the AlarmManager solution I am using is the alarms continue to fire even when the app is closed.

推荐答案

如果您的想法是检查您的 API 是否有新数据并执行后台同步到您的本地数据库或其他数据存储,我想您会喜欢看看这个:

If your idea is to check if your API has new data and perform a background sync to your local database or other data storage, I think you would like to take a look at this:

创建同步适配器

运行同步适配器

同步适配器是在 Android 中实现此目的的推荐方式.使用它的优点是多方面的:

The Sync adapter is the recommended way of achieving this in Android. The pros of using it are multiple:

  • 开箱即用的优化 - 操作系统捆绑调用,使用最合适的窗口以最小的带宽和电池成本运行同步适配器
  • 后台同步组件的生命周期由操作系统内部管理
  • 可以在数据发生更改时通知观察者,以便轻松更新用户界面
  • 运行同步的多种方式 - 每隔一段时间,自动与操作系统消息一起保持 TCP/IP 连接打开或按需

然而,实现这一点需要一些东西,一开始可能会引起一些痛苦:

However, implementing this requires some things, that can cause a bit of a pain at first:

  • 适配器必须使用 ContentProvider
  • 同步适配器使用帐户进行身份验证.如果不需要,则必须提供存根

这篇关于在后台检查新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆