Does anyone know why LoaderManager was excluded from Service?
如另一个答案所述,LoaderManager被明确设计为通过Acivities和Fragments的生命周期管理Loader。由于服务没有这些配置更改要处理,使用LoaderManager不是必需的。
If not is there a way around this?
是的,诀窍是你不需要使用LoaderManager,你可以直接使用你的Loader,它将处理异步加载您的数据和监控任何底层数据更改,这比手动查询数据要好得多。
首先,在创建服务时创建,注册并开始加载Loader。
@Override
public void onCreate() {
mCursorLoader = new CursorLoader(context, contentUri, projection, selection, selectionArgs, orderBy);
mCursorLoader.registerListener(LOADER_ID_NETWORK, this);
mCursorLoader.startLoading();
}
接下来,实现OnLoadCompleteListener< Cursor>在你的服务中处理负载回调。
@Override
public void onLoadComplete(Loader loader, Cursor data) {
// Bind data to UI, etc
}
最后,当服务被销毁时,不要忘记清理Loader。
@Override
public void onDestroy() {
// Stop the cursor loader
if (mCursorLoader != null) {
mCursorLoader.unregisterListener(this);
mCursorLoader.cancelLoad();
mCursorLoader.stopLoading();
}
}