java - 在后台发送 ping - 我这样做对吗?

标签 java android multithreading service

首先让我解释一下这个应用程序:有一个很大的 http 服务器列表,当 ping 到这些服务器时,会回复一个响应。最新的响应和有关服务器的其他所有内容都保存在数据库中。

我已经将 ping 和响应处理简化为一门艺术 - 我只是想知道应该如何设置我的自动 ping 服务。

目前,我已经设置了一个服务(Just Service,而不是 IntentService),它是粘性的,并触发一个线程(只是线程,而不是处理程序或异步任务)被调用,该线程具有无限循环 - 在此循环中,我有一个 Thread.sleep(time) 命令,其中时间可以由用户定义,并且每次重复循环时都会从共享首选项中读取时间。有时该线程可能会 hibernate 24 小时。

在线阅读后,我似乎认为这种线程暂停不是一个好主意,而我应该安排线程以某种方式触发。我需要此 ping 保持开启状态,并且不被 Android 清除。根据我之前的询问,该线程不会被 Android 停止,但我仍然不认为我应该告诉线程 hibernate 24 小时。因此,尽管我非常确定 ping 的时间是准确的,但我不认为这是正确的方法。

我不知道如何安排这些任务,以便它们与用户的计时保持一致,并且不会被 android 清除(可能通过广播和接收器?),同时也不会导致线程挂起。但如果有人能告诉我我所做的事情是错误的,那么我会去做更多研究。

据我所知,即时通讯程序如何检查您是否有新消息要阅读的类似系统以类似的方式工作。然而,在寻找即时消息指南之后,他们要么让线程挂起,要么让一些第三方 API 来处理它,他们只需调用“onMessageReceived”方法,并处理其中的所有内容。

TL;DR - 对于需要长时间延迟的 UI 线程进行无限循环的最佳实践是什么。

最佳答案

您可以将 AlarmManager 设置为特定时间,例如 30m、45m 或适合您情况的任何时间。这样你就不需要在后台运行线程或任何东西。

参见 Smack 的 ServerPingWithAlarmManager.class描述与其推荐相同。

/**
 * Send automatic server pings with the help of {@link AlarmManager}.
 * <p>
 * Smack's {@link PingManager} uses a <code>ScheduledThreadPoolExecutor</code> to schedule the
 * automatic server pings, but on Android, those scheduled pings are not reliable. This is because
 * the Android device may go into deep sleep where the system will not continue to run this causes
 * <ul>
 * <li>the system time to not move forward, which means that the time spent in deep sleep is not
 * counted towards the scheduled delay time</li>
 * <li>the scheduled Runnable is not run while the system is in deep sleep.</li>
 * </ul>
 * That is the reason Android comes with an API to schedule those tasks: AlarmManager. Which this
 * class uses to determine every 30 minutes if a server ping is necessary. The interval of 30
 * minutes is the ideal trade-off between reliability and low resource (battery) consumption.
 * </p>
 * <p>
 * In order to use this class you need to call {@link #onCreate(Context)} <b>once</b>, for example
 * in the <code>onCreate()</code> method of your Service holding the XMPPConnection. And to avoid
 * leaking any resources, you should call {@link #onDestroy()} when you no longer need any of its
 * functionality.
 * </p>
 */

关于java - 在后台发送 ping - 我这样做对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947110/

相关文章:

c - M 次执行后在 C 中完成多线程程序?

java - 如何配置 SpringConfig.java 文件进行 JUnit 测试

java - 用于添加图像的 Wicket 拖放功能

java - 来自 adb install 的 INSTALL_PARSE_FAILED_NO_CERTIFICATES;使用Java 6、Android 5.0.2

Android,应用程序在屏幕旋转时崩溃并打开对话框

linux - 多线程信号量

java - 在java中继承类是否可以,即使它不适合这项工作

java - 通过ListAdapter设置ImageView src

android - 如何向操作栏/工具栏添加后退按钮

c++ - 新算子+OpenMP动态调度子句