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?
问题:
回答1:
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();
}
}
回答2:
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