我使用的重複警報觸發一個BroadcastReceiver(OnAlarmReceiver
),後者又調用WakefulIntentService.sendWakefulWork(context, PmNotificationService.class);
在等待來自單獨線程的響應時保持處理程序和服務處於活動狀態?
下方顯示
protected void doWakefulWork(Intent intent) {
// Load auth information from server
Authentication.loadAuthenticationInformation(this);
if (hasAuthInformation()) {
getRequestParameters().execute(getRequestHandler());
}
}
的doWakefulWork
方法的getRequestParameters().execute(getRequestHandler());
行創建一個對象AjaxRequest
,具有沿着RequestHandler
對象,並且想法是,一旦Ajax請求完成,它就會將信息發送回RequestHandler
。
在這種情況下,處理程序是PmNotificationService
類(它擴展了WakefulIntentService
)。
的問題,因此我的問題的基礎是以下消息:
12月5日至12日:09:08.139:INFO/ActivityManager(52):停止服務:com.sofurry /。服務.PmNotificationService
12月5日至12日:09:08.558:WARN /的MessageQueue(333):{處理程序} 4393e118上死線程發送消息到一個處理程序
12月5日至12日:09:08.558:WARN/MessageQueue(333):java.lang.RuntimeException:Handler {4393e118}將消息發送給處於死亡線程上的處理程序
...
顯然,服務就停止,因爲它已經被罰下場的要求,因爲這要求在另一個線程中運行,因此本公告處理程序是死的運行。
所以我的問題是:我可以保持服務,並因此處理程序活着,直到我得到一個響應(即等待該其他線程)?如果可以的話,我更喜歡它,因爲AjaxRequest對象由其他人維護,並在整個應用程序中使用。
更新
我顯然錯過了一個非常重要點,即從IntentService
,而不是Service
的WakefulIntentService
繼承,這意味着它會自行停止它完成工作後。我目前通過稍微更改doWakefulWork
方法來解決此問題。下面是新的:
@Override
protected void doWakefulWork(Intent intent) {
RequestThread thread = null;
// Load auth information from server
Authentication.loadAuthenticationInformation(this);
if (hasAuthInformation()) {
thread = getRequestParameters().execute(getRequestHandler());
try {
thread.join();
} catch (InterruptedException ignored) {}
}
}
我不知道,如果使用thread.join()
是管理最好的辦法,所以我會離開的問題沒有答案了幾天,我才發佈一個答案,以防萬一有人有更好的解決方案。