开发者

Keep handler and service alive while waiting for response from separate thread?

I'm using a repeating alarm to trigger a BroadcastReceiver (OnAlarmReceiver) which in turn calls WakefulIntentService.sendWakefulWork(context, PmNotificationService.class);

The doWakefulWork method is displayed below

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

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

The getRequestParameters().execute(getRequestHandler()); line creates an AjaxRequest object, along with a RequestHandler object, and the idea was that once the Ajax request is completed, it would send the information back to the RequestHandler.

In this case the handler is the PmNotificationService class (which extends WakefulIntentService).

The problem, and thus the basis of my question is the following message:

05-12 12:09:08.139: INFO/ActivityManager(52): Stopping service: com.sofurry/.services.PmNotificationService

05-12 12:09:08.558: WARN/MessageQueue(333): Handler{4393e118} sending message to a Handler on a dead thread

05-12 12:09:08.558: WARN/MessageQueue(333): java.lang.RuntimeException: Handler{4393e118} sending message to a Handler on a dead thread

...

Obvio开发者_运维知识库usly the service stops running as soon as it has sent off the request, as that request runs in another thread, and as a result hereof the Handler is dead.

So my question is: Can I keep the service and thus the handler alive until I get a response (ie. wait for that other thread)? I would prefer it if I could, as the AjaxRequest object is maintained by someone else, and is used throughout the entire application.

Update

I obviously missed one very important point, namely that the WakefulIntentService inherits from IntentService instead of Service which means it will stop itself after it has done its work. I have currently solved it by changing the doWakefulWork method slightly. Here's the new one:

@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) {}
    }
}

I'm not sure if using thread.join() is the best way to manage this, so I'll leave the question unanswered for a few days, before I post an answer, just in case someone has a better solution for it.


IntentService already uses a background thread for onHandleIntent(). Hence, do not use AsyncTask -- just execute your code in onHandleIntent().

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜