Search code examples
androidcallbacksynchronizationandroid-contentresolverandroid-syncadapter

How to notify calling Activity when SyncAdapter has finished?


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?


Solution

  • 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);
        }
    }