首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncTaskLoader和定向更改

AsyncTaskLoader和定向更改
EN

Stack Overflow用户
提问于 2014-04-22 18:49:00
回答 1查看 641关注 0票数 0

我有一个AsyncTaskLoader在第一次启动时做一些工作。加载器在我的Activity的OnCreate方法中初始化。

代码语言:javascript
复制
if(!startedLoader) {
    getLoaderManager().initLoader(INITIALIZE_DB_LOADER_ID, null, this);
    startedLoader = true;
}

startedLoader是一个布尔值,保存在onSaveInstanceState中,并在onCreate中再次检索。

这避免了我的加载器重新启动。但是现在它不能通过回调传递结果,因为我的侦听器,也就是我的活动本身,已经被销毁了。下面是启动我的Loader的代码:

代码语言:javascript
复制
@Override
public Loader<Boolean> onCreateLoader(int id, Bundle args) {
    return new InitalizeDatabaseLoader(this);
}

我如何避免我的AsyncTaskLoader在方向改变时重新启动,但仍然提供结果?

EN

回答 1

Stack Overflow用户

发布于 2014-04-22 19:48:12

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

你可以在这里找到一个很好的例子:http://developer.android.com/reference/android/content/AsyncTaskLoader.html

最重要的部分是:

代码语言:javascript
复制
/**
 * 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()方法,以便立即交付缓存的结果:

代码语言:javascript
复制
/**
 * 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();
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23217365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档