定期从 Android 中的服务器获取数据(轮询) [英] Periodically fetching data (polling) from the server in Android
问题描述
我正在开发应用程序,在该应用程序中我使用 rest 调用从服务器获取数据并将其添加到视图中.我正确地得到了所有的初始数据.我使用 AsyncTask 来做这件事.
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.
现在我想定期(比如 2 分钟)从服务器获取新数据并将其添加到视图中.定期从 Android 中的服务器获取数据(轮询).
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.
推荐答案
您可以查看 AlarmManager 类来实现.
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);
这是闹钟管理器--
public class MyAlarmManager extends BroadcastReceiver {
Context _context;
@Override
public void onReceive(Context context, Intent intent) {
_context= context;
//connect to server..
}
}
当 AlarmManager 被触发"时,再次连接到服务器并填充您刚刚收到的数据.
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
这篇关于定期从 Android 中的服务器获取数据(轮询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!