Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically fetching data (polling) from the server in Android

I working on the app where I get the data from the server using rest call and add it to the view. I get all the initial data correctly. I use AsyncTask for doing it.

Now I want to periodically (say 2 mins) fetch the new data from the server and add it to view.Periodically fetching data (polling) from the server in Android.

like image 201
Kunal P.Bharati Avatar asked Aug 31 '10 08:08

Kunal P.Bharati


3 Answers

You can checkout the AlarmManager class to do it.

Intent intent = new Intent(this, MyAlarmManager.class);

long scTime = 60*2000;//2mins

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + scTime, pendingIntent);

here's the alarm Manager--

public class MyAlarmManager extends BroadcastReceiver {

    Context _context;
        @Override
        public void onReceive(Context context, Intent intent) {
            _context= context;
            //connect to server..

        }
}

when ever the AlarmManager is 'fired' connect to the server again and populate the data you just recieved.

http://developer.android.com/reference/android/app/AlarmManager.html

like image 177
Umesh Avatar answered Nov 11 '22 09:11

Umesh


follow the tutorial mentioned here. This is exactly what you want to do. Also since server calls are made every few mins this consumes battery. So you can try for server calls only when the server data changes through Push notifications ..

like image 33
sairajat Avatar answered Nov 11 '22 07:11

sairajat


The best way to do it would be to create a service that fetches the data from the server. Afterward if your activity is running, the service can send an intent to the activity with the fetched data.

Or, have the service run when your app runs and have your activity bind to the service when it start up. Then use AIDL or something similar to communicate with the service.
(For example, every time the service has fetched data, it can fire off a callback function in your activity)

like image 45
Miguel Morales Avatar answered Nov 11 '22 09:11

Miguel Morales