AsyncTask in onDestroy() not being executed
Asked Answered
A

1

0

I want to send logout information to server, when the app gets destroyed.

Here's the code:

@Override
protected void onDestroy() {
    try {
        Log.i("myApp", "Activity destroyed");
        SharedPreferences prefs1 = getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
        Log.i("myApp", "step1");
        String response;
        Log.i("myApp", "step2");
        response = HttpPOSTer.logout(EventCodes.LOGOUT, LOGOUT_EVENTCODE, prefs.getString("sessionID", "null"));
        Log.i("myApp", "step3");
        if (response.equals("logout")) {
            Log.i("myApp", "logged out succesfully");
        } else {
            Log.i("myApp", "couldn't perform logout");
        }
        prefs1.edit().clear().commit();
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    } 
    catch (ExecutionException e) {
        e.printStackTrace();
    }   
    super.onDestroy();  
}

But here's the log, when I close the app from home button's long click menu:

enter image description here

I can't even debug here. I place breakpoint, but it never gets fired while debugging.

Is there any reason, why AsyncTask doesn't get called from onDestroy()?

Actinia answered 21/5, 2013 at 11:24 Comment(6)
If "step3" isn't logged, an exception must have occured prior to your logging statement. Please post the code of your HttpPOSTer and the full logcat output.Photon
put your super.onDestroy() after last catch and see it.Berube
@WolframRittmeyer, none exception is thrown. Posted the whole logcat, have a look please. I assure you, everything is ok with HttpPOSTer class.Actinia
@Rahil2952, I've tried that one too, that didn't work for me.Actinia
what is the value of response?Put log there and check its value.Berube
@Rahil2952, the point is, that response never gets value, in other words logoout() never gets called, and therefore step3 never get logged. The question is: why that asynctask doesn't throw any kind of exception?Actinia
M
0

its not a good idea to use asyntask in onDestroy() instead you can have an activity that extends IntentService and give a call to that activity from onDestroy

Musca answered 21/5, 2013 at 11:39 Comment(3)
What's the point of that one? You suggest starting a new intent from onDestroy()? And what should it do?Actinia
because before you get the return value from HttpPOSTer.logout your activity will be destroyed. IntentService will do the task and end itself so put this code inside intentservice and have a toast display the logout stausMusca
Ahh, indeed, I forgot about it! Thank you, I'll try it now.Actinia

© 2022 - 2024 — McMap. All rights reserved.