SyncAdapter始终处于待处理状态

时间:2015-09-24 19:46:09

标签: android synchronization android-contentresolver android-syncadapter swiperefreshlayout

我目前正在开发一款依赖于SyncAdapter从服务器刷新其内容的Android应用。我基本上遵循了这些说明:https://developer.android.com/training/sync-adapters/creating-sync-adapter.html

直到最近才完美地运作。我知道这可能听起来很愚蠢,但老实说我不知道​​我是如何搞砸的:(

设置

我想要同步的所有项目都有一个ContentProvider,因此有一个SyncAdapter和一个帐户。我使用整数标志来确定哪个项目必须同步:

public static final int EVENTS = 0x1;
public static final int NEWS = 0x2;
public static final int SUBSTITUTIONS = 0x4;
public static final int TEACHERS = 0x8;
public static final int ALL = 0xF;

所以在我的onPerformSync我有类似的东西:

ArrayList<ContentProviderOperation> batchList = new ArrayList<>();

int which = extras.getInt(SYNC.ARG, SYNC.ALL);
if((which & SYNC.NEWS) == SYNC.NEWS) { syncNews(provider, batchList, syncResult, 0, 1); }
if((which & SYNC.EVENTS) == SYNC.EVENTS) { syncEvents(provider, batchList, syncResult); }
if((which & SYNC.TEACHERS) == SYNC.TEACHERS) { syncTeachers(provider, batchList, syncResult); }
if((which & SYNC.SUBSTITUTIONS) == SYNC.SUBSTITUTIONS) { syncSubstitutions(provider, batchList, syncResult); }

Log.i(TAG, "Merge solution ready. Applying batch update to database...");
provider.applyBatch(batchList);

因为我也希望用户能够强制刷新,我使用SwipeRefreshLayout启动同步服务:

@Override
public void onRefresh() {
    Log.d(TAG, "Force refresh triggered!");
    SyncUtils.triggerRefresh(SyncAdapter.SYNC.NEWS | SyncAdapter.SYNC.EVENTS);
}

我还希望监控同步状态,因此我在我的片段SyncStatusObserver / onResume中注册/取消注册onPause

private final SyncStatusObserver syncStatusObserver = new SyncStatusObserver() {
    @Override
    public void onStatusChanged(int which) {
        Account account = AuthenticatorService.getAccount(SyncUtils.ACCOUNT_TYPE);
        boolean syncActive = ContentResolver.isSyncActive(account, DataProvider.AUTHORITY);
        boolean syncPending = ContentResolver.isSyncPending(account, DataProvider.AUTHORITY);

        final boolean refresh = syncActive || syncPending;
        Log.d(TAG, "Status change detected. Active: %b, pending: %b, refreshing: %b", syncActive, syncPending, refresh);

        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
               swipeRefreshLayout.setRefreshing(refresh);
            }
        });
    }
};

问题

每当我启动应用程序时,Refresh layout表示同步处于活动状态。我记录了几乎所有内容,发现同步处于挂起状态。每当我尝试强制刷新时,同步都将

  • 变得活跃,做所有的事情,然后回到待定或
  • 永远不会变得活跃并永远处于待定模式

这是一个示例日志:

D/HomeFragment﹕ Status change detected. Active: false, pending: true, refreshing: true
D/HomeFragment﹕ Status change detected. Active: false, pending: true, refreshing: true
D/HomeFragment﹕ Status change detected. Active: true, pending: true, refreshing: true
D/HomeFragment﹕ Status change detected. Active: false, pending: true, refreshing: true

如您所见,永远不会Active: false, pending: false表示同步完成。这真的磨砺了我的齿轮。

更多代码

我在应用程序类中进行存根帐户(以及定期同步)的初始设置:

public static void createSyncAccount(Context context) {
    boolean newAccount = false;
    boolean setupComplete = PreferenceManager
               .getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = AuthenticatorService.getAccount(ACCOUNT_TYPE);
    AccountManager accountManager =
                (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    if (accountManager.addAccountExplicitly(account, null, null)) {    
        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, DataProvider.AUTHORITY, 1);

        // Inform the system that this account is eligible for auto sync when the network is up
        ContentResolver.setSyncAutomatically(account, DataProvider.AUTHORITY, true);

        // Recommend a schedule for automatic synchronization. The system may modify this based
        // on other scheduled syncs and network utilization.
        requestPeriodic(account, SYNC.EVENTS, 172800);
        requestPeriodic(account, SYNC.NEWS, 604800);
        requestPeriodic(account, SYNC.SUBSTITUTIONS, 1800);
        requestPeriodic(account, SYNC.TEACHERS, 2419200);

        newAccount = true;
    }

    // Schedule an initial sync if we detect problems with either our account or our local
    // data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
    // the account list, so wee need to check both.)
    if (newAccount || !setupComplete) {
        triggerRefresh(SYNC.ALL);
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                    .putBoolean(PREF_SETUP_COMPLETE, true).commit();
    }
}

requestPeriodic()如下:

public static void requestPeriodic(Account account, int which, long seconds) {
    Bundle options = new Bundle();
    options.putInt(SYNC.ARG, which);

    ContentResolver.addPeriodicSync(account,
        DataProvider.AUTHORITY, options, seconds);
}

我的triggerRefresh()看起来像:

public static void triggerRefresh(int which) {
    Log.d(TAG, "Force refresh triggered for id: %d", which);

    Bundle options = new Bundle();
    options.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    options.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    options.putInt(SYNC.ARG, which);

    ContentResolver.requestSync(
            AuthenticatorService.getAccount(ACCOUNT_TYPE),
            DataProvider.AUTHORITY,
            options
    );
}

有没有人遇到过类似的问题或对我犯错的想法?​​

更新1

我尝试改变使用SyncStatusObserver的方式。我现在从which标志参数中获取信息,如下所示:

private final SyncStatusObserver syncStatusObserver = new SyncStatusObserver() {
    @Override
    public void onStatusChanged(int which) {
        boolean syncActive = (which & ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE) == ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
        boolean syncPending = (which & ContentResolver.SYNC_OBSERVER_TYPE_PENDING) == ContentResolver.SYNC_OBSERVER_TYPE_PENDING;

        boolean refreshing = syncActive || syncPending;
        // update UI...
    }
};

当我执行此操作时,pending状态似乎是正确的,因此只要适配器启动同步过程,它就会返回false现在适配器一直保持活跃状态​​,boolean refreshing的结果与往常一样。 :/

1 个答案:

答案 0 :(得分:9)

我的syncAdapter遇到了类似的问题......我解决的问题是关闭自动同步...因为你明确触发同步过程就可以删除现有帐户,将内容解析器的setSyncAutomatically设置为false然后再次运行适配器......

ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, false);

我还发布了SyncAdapter的状态更改回调,其中记录了同步过程的状态

private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {

    @Override
    public void onStatusChanged(int which) {
        Log.e("TAG", "Sync Status " + which);
         runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Account account = GenericAccountService.getAccount(SyncUtils.ACCOUNT_TYPE);
                if (account == null) {
                    // GetAccount() returned an invalid value. This shouldn't happen, but
                    // we'll set the status to "not refreshing".
                    //setRefreshActionButtonState(false);
                    return;
                }

                // Test the ContentResolver to see if the sync adapter is active or pending.
                // Set the state of the refresh button accordingly.
                boolean syncActive = ContentResolver.isSyncActive(
                        account, PlacesProvider.PROVIDER_NAME);
                boolean syncPending = ContentResolver.isSyncPending(
                        account, PlacesProvider.PROVIDER_NAME);


                Log.e("TAG", "SYNC PENDING " + syncPending);
                if (!syncActive && !syncPending){
                    Log.e("TAG", "Sync is finished");
                    //if (syncProgressDialog != null) syncProgressDialog.dismiss();
                   // progressDialog.hide();
                }
                else {

                }
                //setRefreshActionButtonState(syncActive || syncPending);
            }
        });
    }
};

在onResume中我注册了SyncStatusObserver

  mSyncStatusObserver.onStatusChanged(0);

    final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
            ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
    mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);

并在onStop中我删除了监听器

  if (mSyncObserverHandle != null) {
        ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
        mSyncObserverHandle = null;
        mSyncStatusObserver = null;
    }