简体   繁体   中英

onLoadFinished not called after coming back from a HOME button press

When using a custom AsyncTaskLoader to download data from a web service, if I press the HOME button in the middle of the loading process and then enter the app again, the onLoadFinished() method is not called. My fragment is calling setRetainInstance(true) in onActivityCreated() and it also calls getLoaderManager.initLoader(0, null, this) in the same method (as is recommended).

While testing, I see that when coming back to the fragment onActivityCreated() is not called so this may be why onLoadFinished() is not called. But where else to put the initLoader() method? I've read in several places that it should not be called in onResume() .

So, any ideas? I have a lot of loaders in various screens in my app and I need to solve this issue in an elegant way.

After looking at Issue 14944 ( http://code.google.com/p/android/issues/detail?id=14944 ), I solved the issue by overriding onStartLoading() in my custom AsyncTaskLoader and call forceLoad() .

An even better solution is to create a custom parent AsyncTaskLoader that looks like this (taken from a suggestion by alexvem from the link above):

public abstract class AsyncLoader<D> extends AsyncTaskLoader<D> {

    private D data;

    public AsyncLoader(Context context) {
        super(context);
    }

    @Override
    public void deliverResult(D data) {
        if (isReset()) {
            // An async query came in while the loader is stopped
            return;
        }

        this.data = data;

        super.deliverResult(data);
    }


    @Override
    protected void onStartLoading() {
        if (data != null) {
            deliverResult(data);
        }

        if (takeContentChanged() || data == null) {
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {
         // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    @Override
    protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        data = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM