我正在使用AsyncTaskLoader
。我有一个已实施LoaderCallbacks
(支持库)的活动。
我调试了断点并放入日志,加载器传递结果,但是第二次没有触发回调onLoadFinished
。奇怪的是 - 当我再次向后旋转时它起作用,当我回到它时,我开始的方向会得到回调。
在我的活动onResume
中:
LoaderManager lm = getSupportLoaderManager();
Loader loader = lm.initLoader(0, null, new LoaderManager.LoaderCallbacks<String>() {
@Override
public Loader<String> onCreateLoader(int i, Bundle bundle) {
Loader<String> loader = new TestLoader(MainActivity.this);
return loader;
}
@Override
public void onLoadFinished(Loader<String> stringLoader, String s) {
Log.d(Application.TAG, "OnLoadFinished " + s);
doStuff(s);
}
@Override
public void onLoaderReset(Loader<String> stringLoader) {
// NOP
}
});
在我的装载机中:
public class TestLoader extends AsyncTaskLoader<String> {
private String mData;
public TestLoader(Context context) {
super(context);
}
// This get's called after a loader is initialized or a loader
// that is alive still is reset
@Override
public void onStartLoading() {
if (mData != null) { // Have our data loaded, just deliver it!
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
// This is called when an Activity or Fragment requests a loader
// to be reset because they want new data
@Override
public void onReset() {
mData = null;
// Ensure that the old task is cancelled if it was running
// We do NOT have to call forceLoad here because onStartLoading
// will get called after this
cancelLoad();
}
// Here we just want to store our own data we got and reset our boolean
@Override
public void deliverResult(String data) {
Log.d(Application.TAG, "deliverResult " + data);
mData = data;
super.deliverResult(mData);
}
@Override
public String loadInBackground() {
// returns content from a content provider ...
}
}
真的让这个人感到困惑,我是Android的新手,所以也许这对其他人来说很明显:)
答案 0 :(得分:25)
如果是getSupportLoaderManager()
,则必须至少在getLoaderManager()
中呼叫onCreate()
/ Activity
,如果是onActivityCreated()
,则必须Fragment
。实际的initLoader()
可能在其他地方。否则,加载程序将处于停止状态,即使完成加载也不会传递结果。我怀疑这是因为加载程序管理器没有将旧的加载器重新附加到新的Activity
,除非上述调用是在新Activity
的{{1}}中进行的。
答案 1 :(得分:1)
你有
Loader loader = lm.initLoader(...)
你应该
Loader loader = new LoaderManager.LoaderCallbacks(...) {...}
并在onResume()
this.getLoaderManager().restartLoader(0, null, this.loader);