Private Static drawable sbackground;
@ Override
Protected void oncreate (bundle state ){
Super. oncreate (State );
Textview label = new textview (this );
Label. settext ("leaks are bad ");
If (sbackground = NULL ){
Sbackground = getdrawable (R. drawable. large_bitmap );
}
Label. setbackgrounddrawable (sbackground );
Setcontentview (Label );
}
Label. setbackgrounddrawable (sbackground); this sentence uses label as the callback of sbackground. Since drawable needs to call label, it will have reference of label.
Textview label = new textview (this); the context is obviously passed to the label as a parameter, so the label has a reference to the context.
If the sbackground cannot be GC, the label cannot be GC, and the context cannot be GC. The resources that reference the context cannot be GC, causing a large memory leakage.
Non-static internal class accesses to external classes are also prone to memory leakage. We recommend that you use static classes and use weakreference to access external classes.
Difference between weakreference and softreference:
The biggest difference is that weakreference will be released immediately (not referenced), and softreference will be released at the latest (with the risk of memory overflow.