Android: Memory leak due to AsyncTask

后端 未结 2 1963
-上瘾入骨i
-上瘾入骨i 2020-12-17 05:20

I\'m stuck with a memory leak that I cannot fix. I identified where it occurs, using the MemoryAnalizer but I vainly struggle to get rid of it. Here is the code:

<         


        
相关标签:
2条回答
  • 2020-12-17 05:24

    Is your thread garbage collected after onPostExecute is called or is it still in the memory?

    A Async Task will not be canceled or destroyed at the moment the activity is dismissed. If your thread is more or less lightweight and finishes after a small time, just keep it running and add a MyActivity.this.isFinishing() clause in the onPostExecute() method.

    Your Task stores a implicit reference to your Activity MyActivity.this because it is a private class inside the activity. This means that your Activity will not be garbage collected until the task exits.

    0 讨论(0)
  • 2020-12-17 05:29

    You can try below code snippet

    protected void onPostExecute(Boolean result) {
        if(YourActivity.this.isFinished()){
            //to smomething here
        }
    }
    
    0 讨论(0)
提交回复
热议问题