Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an Android context leak?

Here's a piece of simplified code:

static Activity longLivedField;

onCreate(...) {     
    longLivedField = this;  // the only write to this field
}

I've seen people claiming this as a context leak, and create fixes for it. The typical fix is to nullify the field at appropriate places. For example, in onPause():

onPause() {
    longLivedField = null;
}
like image 992
dacongy Avatar asked Oct 22 '22 22:10

dacongy


1 Answers

Yes, it is a memory leak if you don't nullify the field in onPause(). You almost certainly never want to retain a static reference to any Activity. What is it that you are trying to achieve?

The Android developer web site contains a handy page describing how to avoid memory leaks like this one:

Avoiding Memory Leaks

like image 123
Charles Harley Avatar answered Nov 15 '22 06:11

Charles Harley