In my Android project I use a custom SyncAdapter which downloads data and stores it in local SQLite database.

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
    }
}

I schedule sychronization from the main Activity using the ContentResolver such as ...

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

Is there a common way the calling Activity is notified when the synchronization has finished?

有帮助吗?

解决方案

You could do this with with ContentResolver.notifyChange().

So in your SyncAdapter you would at something like this:

...
@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);
}
...

In the Activity you then use 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);
    }
}

其他提示

In your activity you can add:

@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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top