How to know when sync is finished?

半城伤御伤魂 提交于 2019-11-27 18:09:13

One solution that I have found is to ditch the ContentResolver completely, and implement my own broadcast. Basically, add this in the sync adapter, at the end of onPerformSync:

Intent i = new Intent(SYNC_FINISHED);
sendBroadcast(i);

And this in the activity:

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(syncFinishedReceiver, new IntentFilter(DataSyncService.SYNC_FINISHED));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(syncFinishedReceiver);
}

private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(Const.TAG, "Sync finished, should refresh nao!!");
    }
};

This seems to work just fine, however I was hoping to find something in the SDK that directly notify me when a sync is finished.

Strange, it does work for me.

In my Activity I have:

  @Override
  protected void onPause() {
    super.onPause();
    ContentResolver.removeStatusChangeListener(mContentProviderHandle);
  }

  @Override
  protected void onResume() {
    super.onResume();
    mContentProviderHandle = ContentResolver.addStatusChangeListener(
        ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE, this);
  }

  @Override
  public void onStatusChanged(int which) {
    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager
        .getAccountsByType(AuthenticatorActivity.PARAM_ACCOUNT_TYPE);

    if (accounts.length <= 0) {
      return;
    }

    updateRefresh(ContentResolver.isSyncActive(accounts[0],
        MyContentProvider.AUTHORITY));
  }

  // Since onStatusChanged() is not called from the main thread
  // I need to update the ui in the ui-thread.
  private void updateRefresh(final boolean isSyncing) {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (isSyncing) {
          mRefreshMenu.setActionView(R.layout.menu_item_refresh);
        } else {
          mRefreshMenu.setActionView(null);
        }
      }
    });
  }
Phuah Yee Keat

I was working on something similar, and I have one more Log.d at the end of the onStatusChanged function, and it wasn't executing!

So after 15 minutes of debugging and trial on error, I realize that I need to add the READ_SYNC_STATS permission, I already have the GET_ACCOUNTS permission though. So, please check that you get the right permission, its not that the "if" doesn't becomes true, its that it bails all the time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!