2016-08-14 22 views
1

首先讓我解釋一下這個應用程序:http服務器有一個很大的列表,當它被ping通時,回覆一個響應。最新的響應和關於服務器的其他一切都保存在數據庫中。在後臺發送ping - 我是否正確地做?

我已經得到了答覆和處理的美術 - 我只是想知道我應該如何設置我的自動ping服務。

目前我已經建立了一個服務(Just Service,而不是IntentService),它是粘性的,並觸發一個線程(只是線程,而不是處理程序或asynctask)被調用,有一個無限循環 - 在這個循環中,我有一個線程.sleep(time)命令,其中時間可以由用戶定義,並且每次循環重複時從共享首選項中讀取。有時候這個線程可以睡24小時。

在網上閱讀後,我似乎認爲這種暫停線程並不是一個好主意,而是我應該安排線程以某種方式觸發。我需要ping這個功能,並且不會被Android清除。從我以前問過的話,線程不會被Android阻止,但我仍然不相信我應該告訴線程24小時睡眠。所以雖然我很確定我的ping的時間準確,但我不認爲這是做到這一點的方法。

我不知道如何安排這些任務,以便他們將保持與用戶的時間一致,而不是由android(可能與廣播和接收器?)清除,同時也不會導致線程掛起。但是如果有人能告訴我我所做的是錯誤的,那麼我會去做更多的研究。

從我可以收集的信息來看,類似的即時通訊程序如何檢查以查看是否有新消息閱讀的系統以類似的方式工作。然而,在尋找即時通訊工具之後,他們要麼讓線程掛起,要麼有一些第三方api來處理它們,他們只是在那裏調用'onMessageReceived'方法,並處理所有內容。

TL; DR-什麼是最好的做法有一個無限循環關閉的UI線程需要延遲很長一段時間。

回答

0

您可以設置一個AlarmManager的特定時間,如30米,45米,或任何適用於您的情況。這樣你就不需要在後臺運行線程或任何東西。

請參閱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> 
*/ 
+0

是的這看起來像我在找什麼。然後我會看看警報管理器。 Thankyou爲例!你在哪裏找到它,我可以問一下嗎? :P – AndroidStudent

+0

ServerPingWithAlarmManager.class中有一個超鏈接,在答案中單擊它。 – uguboz