我有一个AsyncTaskLoader在第一次启动时做一些工作。加载器在我的Activity的OnCreate方法中初始化。
if(!startedLoader) {
getLoaderManager().initLoader(INITIALIZE_DB_LOADER_ID, null, this);
startedLoader = true;
}startedLoader是一个布尔值,保存在onSaveInstanceState中,并在onCreate中再次检索。
这避免了我的加载器重新启动。但是现在它不能通过回调传递结果,因为我的侦听器,也就是我的活动本身,已经被销毁了。下面是启动我的Loader的代码:
@Override
public Loader<Boolean> onCreateLoader(int id, Bundle args) {
return new InitalizeDatabaseLoader(this);
}我如何避免我的AsyncTaskLoader在方向改变时重新启动,但仍然提供结果?
发布于 2014-04-22 19:48:12
您必须扩展deliverResult()方法并将结果保存在内存中,直到activity重新连接到加载器。
你可以在这里找到一个很好的例子:http://developer.android.com/reference/android/content/AsyncTaskLoader.html
最重要的部分是:
/**
* Called when there is new data to deliver to the client. The
* super class will take care of delivering it; the implementation
* here just adds a little more logic.
*/
@Override public void deliverResult(List<AppEntry> apps) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (apps != null) {
onReleaseResources(apps);
}
}
List<AppEntry> oldApps = mApps;
mApps = apps;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(apps);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldApps != null) {
onReleaseResources(oldApps);
}
}此外,您还需要扩展onStartLoading()方法,以便立即交付缓存的结果:
/**
* Handles a request to start the Loader.
*/
@Override protected void onStartLoading() {
if (mApps != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(mApps);
}
// Start watching for changes in the app data.
if (mPackageObserver == null) {
mPackageObserver = new PackageIntentReceiver(this);
}
// Has something interesting in the configuration changed since we
// last built the app list?
boolean configChange = mLastConfig.applyNewConfig(getContext().getResources());
if (takeContentChanged() || mApps == null || configChange) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}https://stackoverflow.com/questions/23217365
复制相似问题