问题
I really like loaders
and their benefits. But i meet a problem which i don't know how to solve.
In my activity i use AsyncTaskLoader to load some data from database and provide cursor to the onLoadFinished(Loader<Cursor> loader, Cursor cursor)
method which is implemented by activity.
Problem is that onLoadFinished()
does not called when activity is in onStop()
state (not finishing()) e.g. incomming call occure.
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayHomeAsUpEnabled(true);
if (bundle != null) {
mFilter = FilterParameters.restoreFromBundle(bundle);
} else {
mFilter = new FilterParameters();
}
setupNavigationMode();
loadData();
}
private void loadData() {
getSupportLoaderManager().initLoader(0, null, this).forceLoad();
}
In loadInBackground()
i just simulate some work in background
private static class GisObjectDatabaseLoader extends AsyncTaskLoader<Cursor> {
public GisObjectDatabaseLoader(Context context) {
super(context);
}
@Override
public Cursor loadInBackground() {
int i = 10;
while (i > 0) {
Log.d(GisObjectDatabaseLoader.class.getSimpleName(), "TICK #" + (10 - i));
try {
Thread.sleep(1000);
i--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Fragment f = getSupportFragmentManager().findFragmentByTag(ProgressDialogFragment.TAG);
if (f == null)
new ProgressDialogFragment().show(getSupportFragmentManager(), ProgressDialogFragment.TAG);
Log.d(GeneralMapActivity.class.getSimpleName(), "SHOW PROGR");
return new GisObjectDatabaseLoader(this);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
Fragment f = getSupportFragmentManager().findFragmentByTag(ProgressDialogFragment.TAG);
if (f != null) {
((ProgressDialogFragment) f).dismissAllowingStateLoss();
}
Log.d(GeneralMapActivity.class.getSimpleName(), "CANCEL PROGR");
}
Loader still working while activity is stopped and 'ticks' to the LogCat
.
I have looked in to AsyncTaskLoader source
void dispatchOnLoadComplete(LoadTask task, D data) {
if (mTask != task) {
if (DEBUG) Slog.v(TAG, "Load complete of old task, trying to cancel");
dispatchOnCancelled(task, data);
} else {
if (isAbandoned()) {
// This cursor has been abandoned; just cancel the new data.
onCanceled(data);
} else {
mLastLoadCompleteTime = SystemClock.uptimeMillis();
mTask = null;
if (DEBUG) Slog.v(TAG, "Delivering result");
deliverResult(data);
}
}
}
Does it mean that I should manually track the loader state when an activity comes to foreground and restart it: if the loader is cancelled and data is still not published (i.e. do the same work one more time)? Is there any way around this problem?
来源:https://stackoverflow.com/questions/17588511/loader-framework-and-activity-lifecycle