1

我正在使用重复警报来触发 BroadcastReceiver ( OnAlarmReceiver),然后调用WakefulIntentService.sendWakefulWork(context, PmNotificationService.class);

doWakefulWork方法如下图

protected void doWakefulWork(Intent intent) {
    // Load auth information from server
    Authentication.loadAuthenticationInformation(this);

    if (hasAuthInformation()) {
        getRequestParameters().execute(getRequestHandler());
    }
}

getRequestParameters().execute(getRequestHandler());行创建了一个AjaxRequest对象以及一个RequestHandler对象,其想法是一旦 Ajax 请求完成,它会将信息发送回RequestHandler.

在这种情况下,处理程序是PmNotificationService类(扩展WakefulIntentService)。

问题,因此我的问题的基础是以下消息:

05-12 12:09:08.139:INFO/ActivityManager(52):停止服务:com.sofurry/.services.PmNotificationService

05-12 12:09:08.558: WARN/MessageQueue(333): Handler{4393e118} 在死线程上向 Handler 发送消息

05-12 12:09:08.558: WARN/MessageQueue(333): java.lang.RuntimeException: Handler{4393e118} 在死线程上向 Handler 发送消息

...

显然,服务在发出请求后立即停止运行,因为该请求在另一个线程中运行,因此 Handler 已死。

所以我的问题是:我可以让服务和处理程序保持活动状态,直到我得到响应(即等待另一个线程)?如果可以的话,我会更喜欢它,因为 AjaxRequest 对象由其他人维护,并在整个应用程序中使用。

更新

我显然错过了一个非常重要的点,即WakefulIntentService继承自IntentService而不是Service意味着它将在完成工作后自行停止。我目前已经通过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) {}
    }
}

我不确定 usingthread.join()是否是管理此问题的最佳方法,因此在发布答案之前,我会在几天内不回答这个问题,以防万一有人有更好的解决方案。

4

1 回答 1

0

IntentService 已经为 onHandleIntent() 使用了后台线程。因此,不要使用 AsyncTask - 只需在 onHandleIntent() 中执行您的代码。

检查https://groups.google.com/forum/#!topic/android-developers/YDrGmFDFUeU

于 2011-10-25T16:55:19.473 回答