原文来自http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html
非静态匿名内部类隐式保存外部类的引用
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exampleOne();
}
private void exampleOne() {
new Thread() {
@Override
public void run() {
while (true) {
SystemClock.sleep(1000);
}
}
}.start();
}
}
上面的代码可能产生内存泄漏,因为线程是非静态的匿名内部类,当Activity的配置发生改变,需要销毁然后新建时,线程保存了旧的Activity的引用,导致旧的Acitvity不能很好的被回收,从而产生了内存泄漏。但是静态内部类不保存外部类的引用,所以可以使用静态内部类替代匿名内部类。
In Android, Handler classes should be static or leaks might occur.
Avoid using non-static inner classes in an activity if instances of the inner class could outlive the activity’s lifecycle.
注意:
AysncTask只能用于短时间的操作——最多几秒钟。
AsyncTasks should only be used for short-lived operations如果内部类(最好使用静态类)需要保存对外部类的引用,使用WeakReference
http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.htmlHandling Configuration Changes with Fragments
当Activity的配置发生改变时,可以使用Fragment保存状态。
配置的改变包含屏幕方向、设备默认的语言和设备默认的字体。
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html