Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
JJD Avatar asked Feb 04 '14 17:02

JJD


2 Answers

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
}
like image 39
HotIceCream Avatar answered Oct 21 '22 03:10

HotIceCream


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);
    }
}
like image 121
Blaz Avatar answered Oct 21 '22 03:10

Blaz