SyncAdapter完成后如何通知调用Activity?

时间:2014-02-04 17:51:00

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

在我的Android项目中,我使用自定义SyncAdapter来下载数据并将其存储在本地SQLite数据库中。

public class CustomSyncAdapter extends AbstractThreadedSyncAdapter {

    public CustomSyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
    }

    @Override
    public void onPerformSync(Account account,
                              Bundle extras,
                              String authority,
                              ContentProviderClient provider,
                              SyncResult syncResult) {

        // 1) Download data via AsyncTask
        // 2) Store data via ContentProvider
    }
}

我使用Activity来安排来自主ContentResolver的同步,例如......

ContentResolver.requestSync(account, Authentication.AUTHORITY, bundle);

同步完成时是否有通知调用Activity的方法?

2 个答案:

答案 0 :(得分:8)

您可以使用ContentResolver.notifyChange()执行此操作。

所以在你的SyncAdapter中,你会遇到这样的事情:

...
@Override
public void onPerformSync(Account account,
                          Bundle extras,
                          String authority,
                          ContentProviderClient provider,
                          SyncResult syncResult) {

    // 1) Download data via AsyncTask
    // 2) Store data via ContentProvider

    getContext().getContentResolver().notifyChange(<your_content_uri>, null, false);
}
...

在活动中,您可以使用ContentResolver.registerContentObserver()

public class MyActivity extends Activity  {

    private ContentObserver mObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
            public void onChange(boolean selfChange) {
                // Do something.
            }
        };
        getContentResolver().registerContentObserver(<your_content_uri>, mObserver);
    }

    @Override
    public void onDestroy() {
        getContentResolver().unregisterContentObserver(mObserver);
    }
}

答案 1 :(得分:3)

在您的活动中,您可以添加:

@Override
public void onResume() {
    super.onResume();
    mSyncMonitor = ContentResolver.addStatusChangeListener(
            ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE
                    | ContentResolver.SYNC_OBSERVER_TYPE_PENDING,
            this
    );
}

@Override
public void onPause() {
    ContentResolver.removeStatusChangeListener(mSyncMonitor);
    super.onPause();
}

@Override
public final void onStatusChanged(int which) {
    // TODO update activity data
}