Naga
Naga

Reputation: 2021

Should I use sync adapter

My app requirement

Login.

Signup.

at 1 min periodic interval fetch data from server and update the UI.

no local db.

For Login and Signup I will use normal HTTP call but for periodic request at 1 min interval I was thinking to use SyncAdapter,

should I use SyncAdapter for this ?, even I have no local db storage.

Is it possible to update the UI from SyncAdapter ?

I have gone through the below links How do I use the Android SyncAdapter?

Sync data between Android App and webserver

Android SyncAdapter use case

Sync data between Android App and webserver

Upvotes: 4

Views: 1894

Answers (2)

HellCat2405
HellCat2405

Reputation: 762

As the official documentation says

The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

I suggest you using SyncAdapter when you need periodic updates even when the user is not using the app. The main strength of the SyncAdapter that it can be switched by Android system even if you don't use the app. So when user enters the app he always have actual data. If you don't have local DB and just need periodic updates use Handler instead.

   int updatePeriod = 60*1000;// one minute in milliseconds
   mHandler = new Handler();
   mRunnable = new Runnable(){
           @Override
           public void run() {
               //update request here
               mHandler.postDelayed(mRunnable, updatePeriod );
             } 
           };
   mRunnable.run(); // missing

This code runs run() every minute. Add your update logic to the run method. Also if you'll be requesting server data every minute you'll just waste device battery. If you want more info on working with the network check this video https://www.youtube.com/watch?v=l5mE3Tpjejs

Upvotes: 3

Knossos
Knossos

Reputation: 16038

Sync adapters are designed to run at off times to keep data current between local and server. Not regularly, and certainly not every minute.

You should probably just implement a Timer, or Handler to control that.

Something similar to this answer.

private int mInterval = 60000; // 60 seconds
private Handler mHandler;

@Override
protected void onCreate(Bundle bundle) {
    ...
    mHandler = new Handler();
    startRepeatingTask();
}

Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
        downloadChangesFromServer();
        mHandler.postDelayed(mStatusChecker, mInterval);
    }
};

void startRepeatingTask() {
    mStatusChecker.run(); 
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
}

Upvotes: 3

Related Questions