Android - 在与ContentResolver.requestSync()请求同步时,如何在同步完成时获得通知

时间:2011-11-22 13:17:04

标签: android sync

我有自己的ContentProviderSyncAdapter,两者都可以。

我将它们设置为与ContentResolver.setSyncAutomatically()自动同步这项工作。我还可以使用Dev Tools测试同步 - >同步测试员。

现在我想从我的应用程序请求同步(如果我们还没有数据)并在完成时收到通知,这样我就可以更新界面(我在同步时显示带有徽标的进度条)。我正在使用ContentResolver.requestSync()执行此操作,但在同步完成时我找不到通知的方法。

有谁知道怎么做?感谢。

3 个答案:

答案 0 :(得分:6)

这是一个完整工作的代码片段,其中包含javadocs,适用于任何想要提供解决方案的人,而不必猜测如何将所有内容放在一起。它建立在Mark的上述答案之上。支持监控多个帐户同步。

import android.accounts.Account;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
 * Sync status observer that reports back via a callback interface when syncing has begun
 * and finished.
 */
public static class MySyncStatusObserver implements SyncStatusObserver {
    /**
     * Defines the various sync states for an account.
     */
    private enum SyncState {
        /**
         * Indicates a sync is pending.
         */
        PENDING,
        /**
         * Indicates a sync is no longer pending but isn't active yet.
         */
        PENDING_ACTIVE,
        /**
         * Indicates a sync is active.
         */
        ACTIVE,
        /**
         * Indicates syncing is finished.
         */
        FINISHED
    }

    /**
     * Lifecycle events.
     */
    public interface Callback {
        /**
         * Indicates syncing of calendars has begun.
         */
        void onSyncsStarted();

        /**
         * Indicates syncing of calendars has finished.
         */
        void onSyncsFinished();
    }

    /**
     * The original list of accounts that are being synced.
     */
    @NonNull private final List<Account> mAccounts;
    /**
     * Map of accounts and their current sync states.
     */
    private final Map<Account, SyncState> mAccountSyncState =
            Collections.synchronizedMap(new HashMap<Account, SyncState>());

    /**
     * The calendar authority we're listening for syncs on.
     */
    @NonNull private final String mCalendarAuthority;
    /**
     * Callback implementation.
     */
    @Nullable private final Callback mCallback;

    /**
     * {@code true} when a "sync started" callback has been called.
     *
     * <p>Keeps us from reporting this event more than once.</p>
     */
    private boolean mSyncStartedReported;
    /**
     * Provider handle returned from
     * {@link ContentResolver#addStatusChangeListener(int, SyncStatusObserver)} used to
     * unregister for sync status changes.
     */
    @Nullable private Object mProviderHandle;

    /**
     * Default constructor.
     *
     * @param accounts the accounts to monitor syncing for
     * @param calendarAuthority the calendar authority for the syncs
     * @param callback optional callback interface to receive events
     */
    public MySyncStatusObserver(@NonNull final Account[] accounts,
            @NonNull final String calendarAuthority, @Nullable final Callback callback) {
        mAccounts = Lists.newArrayList(accounts);
        mCalendarAuthority = calendarAuthority;
        mCallback = callback;
    }

    /**
     * Sets the provider handle to unregister for sync status changes with.
     */
    public void setProviderHandle(@Nullable final Object providerHandle) {
        mProviderHandle = providerHandle;
    }

    @Override
    public void onStatusChanged(int which) {
        for (final Account account : mAccounts) {
            if (which == ContentResolver.SYNC_OBSERVER_TYPE_PENDING) {
                if (ContentResolver.isSyncPending(account, mCalendarAuthority)) {
                    // There is now a pending sync.
                    mAccountSyncState.put(account, SyncState.PENDING);
                } else {
                    // There is no longer a pending sync.
                    mAccountSyncState.put(account, SyncState.PENDING_ACTIVE);
                }
            } else if (which == ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE) {
                if (ContentResolver.isSyncActive(account, mCalendarAuthority)) {
                    // There is now an active sync.
                    mAccountSyncState.put(account, SyncState.ACTIVE);

                    if (!mSyncStartedReported && mCallback != null) {
                        mCallback.onSyncsStarted();
                        mSyncStartedReported = true;
                    }
                } else {
                    // There is no longer an active sync.
                    mAccountSyncState.put(account, SyncState.FINISHED);
                }
            }
        }

        // We haven't finished processing sync states for all accounts yet
        if (mAccounts.size() != mAccountSyncState.size()) return;

        // Check if any accounts are not finished syncing yet. If so bail
        for (final SyncState syncState : mAccountSyncState.values()) {
            if (syncState != SyncState.FINISHED) return;
        }

        // 1. Unregister for sync status changes
        if (mProviderHandle != null) {
            ContentResolver.removeStatusChangeListener(mProviderHandle);
        }

        // 2. Report back that all syncs are finished
        if (mCallback != null) {
            mCallback.onSyncsFinished();
        }
    }
}

以下是实施:

public class MyActivity extends Activity implements MySyncStatusObserver.Callback {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.some_layout);

        // Retrieve your accounts
        final Account[] accounts = AccountManager.get(this).getAccountsByType("your_account_type");

        // Register for sync status changes
        final MySyncStatusObserver observer = new MySyncStatusObserver(accounts, "the sync authority", this);
        final Object providerHandle = ContentResolver.addStatusChangeListener(
            ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE |
                    ContentResolver.SYNC_OBSERVER_TYPE_PENDING, observer);
        // Pass in the handle so the observer can unregister itself from events when finished.
        // You could optionally save this handle at the Activity level but I prefer to
        // encapsulate everything in the observer and let it handle everything
        observer.setProviderHandle(providerHandle);

        for (final Account account : accounts) {
            // Request the sync
            ContentResolver.requestSync(account, "the sync authority", null);
        }
    }

    @Override
    public void onSyncsStarted() {
        // Show a refresh indicator if you need
    }

    @Override
    public void onSyncsFinished() {
        // Hide the refresh indicator if you need
    }
}

答案 1 :(得分:5)

addStatusChangeListener() 会在同步完成时通知您,它只是以稍微迂回的方式通知您:SyncStatusObserver.onStatusChanged()被调用以通知您状态已更改。然后,您必须致电ContentResolver.isSyncPending()ContentResolver.isSyncActive()以检查新状态。

...
ContentResolver.addStatusChangeListener(
        ContentResolver.SYNC_OBSERVER_TYPE_PENDING
            | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE,
        new MySyncStatusObserver());
...

private class MySyncStatusObserver implements SyncStatusObserver {
    @Override
    public void onStatusChanged(int which) {
        if (which == ContentResolver.SYNC_OBSERVER_TYPE_PENDING) {
            // 'Pending' state changed.
            if (ContentResolver.isSyncPending(mAccount, MY_AUTHORITY)) {
                // There is now a pending sync.
            } else {
                // There is no longer a pending sync.
            }
        } else if (which == ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE) {
            // 'Active' state changed.
            if (ContentResolver.isSyncActive(mAccount, MY_AUTHORITY)) {
                // There is now an active sync.
            } else {
                // There is no longer an active sync.
            }
        }
    }
}

另外需要注意:在我的测试中,当我请求同步时,我的onStatusChanged()方法被调用了四次:

  1. pending更改为true
  2. pending更改为false
  3. active已更改为true
  4. active更改为false
  5. 所以看起来在挂起和活动之间有一个窗口,其中两个都设置为false,即使活动同步即将开始。

答案 2 :(得分:4)

使用addStatusChangeListener()会在同步为SYNC_OBSERVER_TYPE_ACTIVESYNC_OBSERVER_TYPE_PENDING时为您提供回调。没有完成的事件真是奇怪。

这是Felix建议的workaround。他建议你放弃ContentResolver支持广播。