android - 定期轮询服务器并将响应显示为通知

Ane*_*esh 3 notifications android

我正在构建一个 android 应用程序,我需要每三个小时从服务器获取一些通知数据(文本),并使用 NotificationManager 将其显示为通知。我看过这里这里,但它们对我来说似乎很混乱。

我怎样才能做到这一点?

Sub*_*sed 5

使用带有挂起意图的 AlarmManager 来启动服务,从您的服务内部对服务器进行 API 调用,创建通知,然后停止服务。

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将设置一个挂起的意图,以在您使用 YOUR_INTERVAL 变量设置的任何时间间隔内启动您的服务。从这里开始,只需创建“MyService”类即可进行 API 调用,并在收到服务器响应后构建通知。