Android Loader源码分析(一)

Loader是Android3.0之后推出的一个异步加载类,他可以方便我们在Activity和Fragment中异步加载数据,Loader有一下特点

  • 可用于每个Activity和Fragment。
  • 支持异步加载数据。
  • 监控其数据源并在内容变化时传递新结果。
  • 在某一配置更改后重建加载器时,会自动重新连接上一个加载器的游标。 因此,它们无需重新查询其数据。

Loader的使用

  • initLoader()保证一个加载器被初始化并激活.它具有两种可能的结果:
    • 如果ID所指的加载器已经存在,那么这个加载器将被重用.
    • 如果加载器不存在,initLoader()就触发LoaderManager.LoaderCallbacks的方法onCreateLoader().这是你实例化并返回一个新加载器的地方.
  • 想要丢弃旧的数据,使用restartLoader()

示例代码

//示例代码
//1:id  2:可选参数  3:回调函数
getLoaderManager().initLoader(1, null, mCallback);
getLoaderManager().restartLoader(1, null, mCallback);
getLoaderManager().destroyLoader(1);
  
LoaderManager.LoaderCallbacks mCallback = new LoaderManager.LoaderCallbacks() {
    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        Log.e("MainActivity", "onCreateLoader---" + id);
        Loader loader = new Loader<>(MainActivity.this);
        return loader;
    }
 
    @Override
    public void onLoadFinished(Loader loader, Object data) {
        Log.e("MainActivity", "onLoadFinished");
    }
 
    @Override
    public void onLoaderReset(Loader loader) {
        Log.e("MainActivity", "onLoaderReset");
    }
};

 
 

ps:当onCreateLoader的返回值为null的时候,onCreateLoader会被回调两次,其中第二次是在Activity的onStart 方法中回调的

getLoaderManager()获取到的LoaderManager的实现类是LoaderManagerImpl
LoaderManagerImpl的initLoader方法:

public  Loader initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks callback) {
    if (mCreatingLoader) {
        throw new IllegalStateException("Called while creating a loader");
    }
 
    LoaderInfo info = mLoaders.get(id);
 
    if (info == null) {
        // Loader doesn't already exist; create.
10      info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks)callback);
    } else {
        info.mCallbacks = (LoaderManager.LoaderCallbacks)callback;
    }
    if (info.mHaveData && mStarted) {
        // If the loader has already generated its data, report it now.
        info.callOnLoadFinished(info.mLoader, info.mData);
    }
 
    return (Loader)info.mLoader;
}
 
 

initLoader()会先通过mLoaders.get(id)来根据id获取LoaderInfo对象。如果Activity或Fragment是第一次调用initLoader(),则获取到的LoaderInfo对象为null。
如果LoaderInfo对象为null,则接着调用createAndInstallLoader()方法(第十行)
下面是createAndInstallLoader()方法的实现

private LoaderInfo createAndInstallLoader(int id, Bundle args,
        LoaderManager.LoaderCallbacks callback) {
    try {
        mCreatingLoader = true;
        LoaderInfo info = createLoader(id, args, callback);
        installLoader(info);
        return info;
    } finally {
        mCreatingLoader = false;
    }
}
  
private LoaderInfo createLoader(int id, Bundle args,
        LoaderManager.LoaderCallbacks callback) {
    LoaderInfo info = new LoaderInfo(id, args,  (LoaderManager.LoaderCallbacks)callback);  //创建LoaderInfo对象
    Loader loader = callback.onCreateLoader(id, args);   //这里是第一调用onCreateLoader()来创建一个loader对象(可能为null)
    info.mLoader = (Loader)loader;
    return info;
}
  
void installLoader(LoaderInfo info) {
    mLoaders.put(info.mId, info);
    if (mStarted) {
        // The activity will start all existing loaders in it's onStart(),
        // so only start them here if we're past that point of the activitiy's
        // life cycle  这里如果initloader方法如果在onStart()之后,则在这里start第二次
        info.start();
    }
}
 
 

createAndInstallLoader会调用createLoaderinstallLoader

installLoader方法里面的注释说
The activity will start all existing loaders in it's onStart(),
Activity的onStart()方法:

protected void onStart() {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
    mCalled = true;
    mFragments.doLoaderStart();
    getApplication().dispatchActivityStarted(this);
}
  
//mFragments.doLoaderStart()方法最终会调用到LoaderManager的doStart()方法
void doStart() {
    if (mStarted) {
        RuntimeException e = new RuntimeException("here");
        e.fillInStackTrace();
        Log.w(TAG, "Called doStart when already started: " + this, e);
        return;
    }
     
    mStarted = true;
 
    // Call out to sub classes so they can start their loaders
    // Let the existing loaders know that we want to be notified when a load is complete
    for (int i = mLoaders.size()-1; i >= 0; i--) {
        mLoaders.valueAt(i).start();
    }    //在这里会 start all existing loaders
}

在Activity的onStart()生命周期方法中,最终会调用到LoaderManagerImpl的doStart()方法,在doStart()方法中会有一个for循环,会把所有存在的Loader都调用一次start()方法
接着就应该是LoaderInfo的start方法:

void start() {
    if (mRetaining && mRetainingStarted) {
        // Our owner is started, but we were being retained from a
        // previous instance in the started state...  so there is really
        // nothing to do here, since the loaders are still started.
        mStarted = true;
        return;
    }
 
    if (mStarted) {
        // If loader already started, don't restart.
        return;
    }
 
    mStarted = true;
     
    //这里createLoader方法里面第一次调用onCreateLoader()如果返回不为空,则不再调用第二次
    if (mLoader == null && mCallbacks != null) {
       mLoader = mCallbacks.onCreateLoader(mId, mArgs);
    }
    if (mLoader != null) {
        if (mLoader.getClass().isMemberClass()
                && !Modifier.isStatic(mLoader.getClass().getModifiers())) {
            throw new IllegalArgumentException(
                    "Object returned from onCreateLoader must not be a non-static inner member class: "
                    + mLoader);
        }
        if (!mListenerRegistered) {
            mLoader.registerListener(mId, this);
            mLoader.registerOnLoadCanceledListener(this);
            mListenerRegistered = true;
        }
        mLoader.startLoading();
    }
}

So:如果onCreateLoader返回为null,则onCreateLoader则会执行两次。

start方法中有一个非常重要的成员——mLoader(第一次调用onCreateLoader方法返回的Loader对象)
start方法最后会调用mLoader.startLoading();
代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.e("gj", "before");
    getLoaderManager().initLoader(1, null, mCallback);
    Log.e("gj", "after");
}
 
@Override
protected void onStart() {
    Log.e("gj", "before_onStart");
    super.onStart();
    Log.e("gj", "after_onStart");
}
LoaderManager.LoaderCallbacks mCallback = new LoaderManager.LoaderCallbacks() {
    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        Log.e("gj", "onCreateLoader---" + id);
        return null;
    }
 
    @Override
    public void onLoadFinished(Loader loader, Object data) {
        Log.e("gj", "onLoadFinished");
    }
 
    @Override
    public void onLoaderReset(Loader loader) {
        Log.e("gj", "onLoaderReset");
    }
};
 
 

输出日志

before_onCreate
onCreateLoader---1
after_onCreate
before_onStart
onCreateLoader---1
after_onStart

当在onStart()之后initLoader的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
 
@Override
protected void onStart() {
    Log.e("gj", "before_onStart");
    super.onStart();
    Log.e("gj", "after_onStart");
}
 
@Override
protected void onResume() {
    super.onResume();
    Log.e("gj", "before_onResume");
    getLoaderManager().initLoader(1, null, mCallback);
    Log.e("gj", "after_onResume");
}
 
LoaderManager.LoaderCallbacks mCallback = new LoaderManager.LoaderCallbacks() {
    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        Log.e("gj", "onCreateLoader---" + id);
        return null;
    }
 
    @Override
    public void onLoadFinished(Loader loader, Object data) {
        Log.e("gj", "onLoadFinished");
    }
 
    @Override
    public void onLoaderReset(Loader loader) {
        Log.e("gj", "onLoaderReset");
    }
 
};
 
 

输出日志:

before_onStart
after_onStart
before_onResume
onCreateLoader---1
onCreateLoader---1
after_onResume

到这里只分析到mLoader.startLoading(); 知道了为什么onCreateLoader返回为null的话他会被调用两次
异步执行的过程,接下来请看Android Loader源码分析(二)

你可能感兴趣的:(Android Loader源码分析(一))