AsyncTaskLoader 无休止的 onCanceled 调用

AsyncTaskLoader endless onCanceled call

我正在创建一个基于 http://developer.android.com/reference/android/content/AsyncTaskLoader.html. When I run my app, according to my logging, the app endlessly oscillates between loadInBackground and onCanceled. Does anyone know why this error might happen? My BroadcastReceiver is based on Proper notification of AsyncTaskLoader about data changes from background thread 的 AsyncTaskLoader。

这是我的 loadInBackground 方法:

 @Override     
 public List<MyItem> loadInBackground() {     

    List<MyItem> items = createDummyData();

    LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(RECEIVER_FILTER_STRING));     

     Log.d(TAG,”custom loader send broadcast from background and send items: "+items.size());     

     return items;      
}

这是我的onStartLoading

@Override
  protected void onStartLoading() {
    Log.d(TAG, "items loader onStartLoading");
    if (null != mData) {
      Log.d(TAG, "items loader onStartLoading mData not null");
      //someone is calling to start the loader, so if we have data, deliver it now
      deliverResult(mData);
    }

    if (null == mReceiver) {
      Log.d(TAG, "items loader onStartLoading register receiver");
      mReceiver = new LoaderBroadcastReceiver(this);
      LocalBroadcastManager.getInstance(getContext()).
          registerReceiver(mReceiver, new IntentFilter(RECEIVER_FILTER_STRING));
    }

    if (takeContentChanged() || null == mData) {
      //if data has changed since the last time it was loaded or is not available, then:
      Log.d(TAG, "items loader onStartLoading onChange forceLoad");
      forceLoad();
    }
  }

这是我的接收器

class LoaderBroadcastReceiver extends BroadcastReceiver {
    private Loader loader;

    public LoaderBroadcastReceiver(Loader loader) {
      this.loader = loader;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
      Log.d(TAG, "loader receiver informing of oonContentChagned");
      loader.onContentChanged();
    }
  }

当它在后台加载时,它发送广播,广播调用 onContentChanged() 这就是当前加载程序被取消并重新运行的原因。

您应该简单地删除 BroadcastReceiver,否则 BroadcastReceiver 不应调用 onContentChanged()。

根据您引用的link,BroadcastReceiver 用于类似这样的事情,例如您加载程序将文件列表加载到文件夹中,并且由于某种原因您知道添加了新文件,因此您发送广播(不是来自您的加载程序)并强制加载程序重新运行和获取新内容。

public void onContentChanged () Added in API level 11

Called when Loader.ForceLoadContentObserver detects a change. The default implementation checks to see if the loader is currently started; if so, it simply calls forceLoad();