3

我真的很喜欢loaders和他们的好处。但是我遇到了一个我不知道如何解决的问题。在我的活动中,我使用 AsyncTaskLoader 从数据库加载一些数据并将光标提供给onLoadFinished(Loader<Cursor> loader, Cursor cursor)活动实现的方法。问题是onLoadFinished()当活动处于状态时不调用onStop()(不是finish()),例如发生来电。

    @Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    mActionBar.setDisplayShowTitleEnabled(false);
    mActionBar.setDisplayHomeAsUpEnabled(true);

    if (bundle != null) {
        mFilter = FilterParameters.restoreFromBundle(bundle);
    } else {
        mFilter = new FilterParameters();
    }
    setupNavigationMode();
    loadData();
}


private void loadData() {
     getSupportLoaderManager().initLoader(0, null, this).forceLoad();
}

loadInBackground()我只是在后台模拟一些工作

    private static class GisObjectDatabaseLoader extends AsyncTaskLoader<Cursor> {
    public GisObjectDatabaseLoader(Context context) {
        super(context);
    }

    @Override
    public Cursor loadInBackground() {
        int i = 10;
        while (i > 0) {
            Log.d(GisObjectDatabaseLoader.class.getSimpleName(), "TICK #" + (10 - i));
            try {
                Thread.sleep(1000);
                i--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
    Fragment f = getSupportFragmentManager().findFragmentByTag(ProgressDialogFragment.TAG);
    if (f == null)
        new ProgressDialogFragment().show(getSupportFragmentManager(), ProgressDialogFragment.TAG);
    Log.d(GeneralMapActivity.class.getSimpleName(), "SHOW PROGR");
    return new GisObjectDatabaseLoader(this);
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
    Fragment f = getSupportFragmentManager().findFragmentByTag(ProgressDialogFragment.TAG);
    if (f != null) {
        ((ProgressDialogFragment) f).dismissAllowingStateLoss();
    }
    Log.d(GeneralMapActivity.class.getSimpleName(), "CANCEL PROGR");
}

加载程序仍在工作,而活动停止并“滴答”到LogCat. 我查看了AsyncTaskLoader 源

  void dispatchOnLoadComplete(LoadTask task, D data) {
    if (mTask != task) {
        if (DEBUG) Slog.v(TAG, "Load complete of old task, trying to cancel");
        dispatchOnCancelled(task, data);
    } else {
        if (isAbandoned()) {
            // This cursor has been abandoned; just cancel the new data.
            onCanceled(data);
        } else {
            mLastLoadCompleteTime = SystemClock.uptimeMillis();
            mTask = null;
            if (DEBUG) Slog.v(TAG, "Delivering result");
            deliverResult(data);
        }
    }
}

这是否意味着当活动进入前台时我应该手动跟踪加载器状态并重新启动它:如果加载器被取消并且数据仍未发布(即再次执行相同的工作)?有没有办法解决这个问题?

4

0 回答 0