tags:

views:

70

answers:

2

Hello All,

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.

A: 

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)

Miguel Morales
A: 

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

Umesh
Hi Umesh,Tried your solution. I am using AlarmManager as inner class which in turn does async calls which updates my GUI. But I am getting this error:"Unable to instantiate receiver".I have added this to AndroidManifest.xml file: <receiver android:name="OuterClass$InnerClass" android:enabled="true"/>Whats the issue?
Kunal P.Bharati
as you can see AlarmManager is a public class which extends a BroadcastReciever and needs to be written in a different file. (In the above case the file's name would be MyAlarmManager.java)In the manifest file:<receiver android:name=".MyAlarmManager" android:enabled="true"> <intent-filter> </intent-filter> </receiver>keeping it as an inner class might be the issue here.
Umesh