AsyncTaskLoader和方向更改

时间:2014-04-22 10:49:00

标签: android android-loadermanager android-loader

我有一个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在方向更改时重新启动但仍会传递结果?

1 个答案:

答案 0 :(得分:2)

您必须扩展deliverResult()方法并将结果保留在内存中,直到活动重新连接到加载程序。

你可以在这里找到一个很好的例子: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();
    }
}