Android的 - 定期轮询服务器,并作为通知显示响应 [英] android - Periodically polling a server and displaying response as a notification
问题描述
我建立一个Android应用程序,我需要从一个服务器每隔三小时取一些通知数据(文本),并显示为使用NotificationManager通知。我看了<一个href=\"http://simpleandroidtutorials.blogspot.in/2012/06/periodically-update-data-from-server-in.html\"相对=nofollow>这里和这里一>但他们似乎pretty混乱给我。
I'm building an android app where I need to fetch some notification data (text) from a server every three hours and display it as a notification using NotificationManager. I've looked here and here but they seem pretty confusing to me.
我怎样才能得到这个工作?
How can I get this done?
推荐答案
使用AlarmManager与挂起的意图启动一个服务,使API调用服务器从服务中,创建通知,则停止该服务。
Use AlarmManager with a pending intent to start a service, make the API call to the server from within your service, create the notification, then stop the service.
/**
* Set up recurring location updates using AlarmManager
*/
public void setUpAlarm(Application context) {
Intent intent = new Intent(context, MyService.class);
PendingIntent pending_intent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm_mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm_mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), YOUR_INTERVAL, pending_intent);
}
以上code将设置一个悬而未决的意图,开始您的服务,为任何时间间隔来与YOUR_INTERVAL变量设置。从这里,您只需建立则将MyService级,让您的API调用,建立自己的通知,一旦你从服务器的响应。
The above code will set a pending intent to start your service for whatever interval you set with the YOUR_INTERVAL variable. From here, just create your "MyService" class to make your API call and build your notification once you get a response from the server.
这篇关于Android的 - 定期轮询服务器,并作为通知显示响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!