您可以从服务中使用 LoaderManager 吗?
我有一个使用自定义加载器和游标设置的数据加载系统,该系统在活动和片段中运行良好,但服务中没有 LoaderManager (我可以找到)。有谁知道为什么 LoaderManager 被排除在服务之外?如果没有,有办法解决这个问题吗?
I have a data loading system set up using a custom Loader and Cursor that is working great from Activities and Fragments but there is no LoaderManager (that I can find) in Service. Does anyone know why LoaderManager was excluded from Service? If not is there a way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如另一个答案中所述,
LoaderManager
被明确设计为通过Acivities
和Fragments
的生命周期来管理Loaders
。由于Services
不需要处理这些配置更改,因此没有必要使用LoaderManager
。是的,诀窍是您不需要使用
LoaderManager
,您可以直接使用Loader
,它将处理异步加载数据并监控任何底层数据为您进行更改,这比手动查询数据要好得多。首先,创建、注册并在创建
Service
时开始加载Loader
。接下来,在
Service
中实现OnLoadCompleteListener
来处理加载回调。最后,当
Service
被销毁时,不要忘记清理您的Loader
。As stated in the other answer,
LoaderManager
was explicitly designed to manageLoaders
through the lifecycles ofAcivities
andFragments
. SinceServices
do not have these configuration changes to deal with, using aLoaderManager
isn't necessary.Yes, the trick is you don't need to use a
LoaderManager
, you can just work with yourLoader
directly, which will handle asynchronously loading your data and monitoring any underlying data changes for you, which is much better than querying your data manually.First, create, register, and start loading your
Loader
when yourService
is created.Next, implement
OnLoadCompleteListener<Cursor>
in yourService
to handle load callbacks.Lastly, don't forget clean up your
Loader
when theService
is destroyed.不幸的是,没有。加载器是为活动和片段设计的,以便干净地处理活动和片段中发生的配置更改。即旋转您的设备并重新附加到现有数据。
服务没有任何配置更改,它将位于后台,直到完成或系统强制终止它。因此,假设您在服务的后台线程上执行代码(无论如何您都应该这样做),则没有理由使用加载程序。只需拨打您需要的电话即可查询您的数据。
因此,如果您的 Service 只是一个 IntentService,您可以在 onHandleIntent() 方法中编写逻辑来查询游标支持的数据。
http://developer.android.com/guide/components/loaders.html
Unfortunately, no. Loaders were designed for activities and fragments in order to cleanly handle configuration changes that occur in Activites and Fragments. i.e. Rotating your device and re-attaching to the existing data.
A service does not have any configuration changes, it will sit in the background until it completes or the system is forced to kill it. So assuming you're executing your code on a background thread in your Service (which you should be anyways), theres just no reason to use a Loader. Simply make the calls you need to query your data.
So if your Service is just an IntentService, you can write your logic to query your cursor-backed data in the onHandleIntent() method.
http://developer.android.com/guide/components/loaders.html