Android AsyncTaskLoader doesn't start loadInBackground?

后端 未结 6 1466
有刺的猬
有刺的猬 2021-01-30 10:23

I am trying to implement a loader example on Android but can\'t get it to start the loader. I am using the following code. It will hit the \"Create Loader\" but it will never re

6条回答
  •  醉话见心
    2021-01-30 10:41

    rrayst's advice is quite compact. If you write your method like this:

    protected void onStartLoading() {
        forceLoad();
    }
    

    you ''ll notice that when a child activity comes up and then you return to the parent one, onStartLoading (and so loadInBackground) are called again!

    What can you do? Set an internal variable (mContentChanged) to true inside the constructor; then check this variable inside onStartLoading. Only when it's true, start loading for real:

    package example.util;
    
    import android.content.Context;
    import android.support.v4.content.AsyncTaskLoader;
    
    public abstract class ATLoader extends AsyncTaskLoader {
    
        public ATLoader(Context context) {
            super(context);
            // run only once
            onContentChanged();
        }
    
        @Override
        protected void onStartLoading() {
            // That's how we start every AsyncTaskLoader...
            // -  code snippet from  android.content.CursorLoader  (method  onStartLoading)
            if (takeContentChanged()) {
                forceLoad();
            }
        }
    
        @Override
        protected void onStopLoading() {
            cancelLoad();
        }
    }
    

提交回复
热议问题