您可以从服务使用LoaderManager?您可以、LoaderManager

2023-09-04 06:12:40 作者:太过炽热

我有一个数据加载系统设置使用自定义的装载机和光标的是伟大的工作,从活动和片段,但没有在服务没有LoaderManager(我能找到)。没有人知道为什么LoaderManager被排除服务?如果不是有没有办法解决?

解决方案   

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

正如其他回答说, LoaderManager 是明确设计管理装载机到 Acivities 和片段。由于服务没有这些配置的变化来处理,使用 LoaderManager 是没有必要的。

  

如果不是有没有办法解决?

是的,关键是你不需要使用 LoaderManager ,你可以与你的装载机直接,这将处理异步加载数据和监测您的任何基础数据的变化,这是比手动查询数据要好得多。

首先,创建,注册,并开始加载你的装载机当你的服务创建。

  @覆盖
公共无效的onCreate(){
    mCursorLoader =新CursorLoader(背景下,contentUri,投影,选择,selectionArgs两个,排序依据);
    mCursorLoader.registerListener(LOADER_ID_NETWORK,这一点);
    mCursorLoader.startLoading();
}
 

其次,实施 OnLoadCompleteListener<光标> 服务来处理负载回调

  @覆盖
公共无效的onLoadComplete(装载机<光标>装载机,光标数据){
    //将数据绑定到用户界面,等等
}
 
LoaderManager使用详解 4 实例 AppListLoader

最后,别忘了清理你的装载机服务被销毁。

  @覆盖
公共无效的onDestroy(){

    //停止光标装载机
    如果(mCursorLoader!= NULL){
        mCursorLoader.unregisterListener(本);
        mCursorLoader.cancelLoad();
        mCursorLoader.stopLoading();
    }
}
 

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?

解决方案

Does anyone know why LoaderManager was excluded from Service?

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?

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.

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();
}

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
}

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();
    }
}