您可以使用来自服务的 LoaderManager 吗? [英] Can you use a LoaderManager from a Service?

查看:25
本文介绍了您可以使用来自服务的 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?

推荐答案

有谁知道为什么 LoaderManager 被排除在服务之外?

Does anyone know why LoaderManager was excluded from Service?

如另一个答案所述,LoaderManager 被明确设计为在 AcivitiesFragments 的生命周期中管理 Loaders代码>.由于 Services 不需要处理这些配置更改,因此不需要使用 LoaderManager.

As stated in the other answer, LoaderManager was explicitly designed to manage Loaders through the lifecycles of Acivities and Fragments. Since Services do not have these configuration changes to deal with, using a LoaderManager isn't necessary.

如果没有,有没有办法解决这个问题?

If not is there a way around this?

是的,诀窍是您不需要使用 LoaderManager,您可以直接使用您的 Loader,它将处理异步加载您的数据和监控为您更改任何基础数据,这比手动查询您的数据要好得多.

Yes, the trick is you don't need to use a LoaderManager, you can just work with your Loader 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.

首先,创建、注册并在您的 Service 创建后开始加载您的 Loader.

First, create, register, and start loading your Loader when your Service is created.

@Override
public void onCreate() {
    mCursorLoader = new CursorLoader(context, contentUri, projection, selection, selectionArgs, orderBy);
    mCursorLoader.registerListener(LOADER_ID_NETWORK, this);
    mCursorLoader.startLoading();
}

接下来,在您的 Service 中实现 OnLoadCompleteListener 以处理加载回调.

Next, implement OnLoadCompleteListener<Cursor> in your Service to handle load callbacks.

@Override
public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
    // Bind data to UI, etc
}

最后,不要忘记在 Service 被销毁时清理你的 Loader.

Lastly, don't forget clean up your Loader when the Service is destroyed.

@Override
public void onDestroy() {

    // Stop the cursor loader
    if (mCursorLoader != null) {
        mCursorLoader.unregisterListener(this);
        mCursorLoader.cancelLoad();
        mCursorLoader.stopLoading();
    }
}

这篇关于您可以使用来自服务的 LoaderManager 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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