原因:匿名内部类会持有外部类的引用,当内部类进行延时操作的时候,如果外部类是Activity,那么在执行destroy后,并不会被销毁,从而导致内存泄漏。
Handler:
解决方案:
1.改为静态内部类(静态内部类不持有外部类的引用)+弱引用
private static MyHandler extends Handler { @Override public void handleMessage(Message msg) { //TODO handle message... } };
但是,发现不能持有外部引用,就不能调用外部类方法,因此我们内部改成持有外部类的弱引用。
public class MainActivity extends Activity { /** * Instancesof static inner classes do not hold an implicit * referenceto their outer class. */ private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity; public MyHandler(MainActivity activity) { mActivity= new WeakReference<MainActivity>(activity); } @Override public void handleMessage(Message msg) { MainActivity activity = mActivity.get(); if(activity != null) { // ... } } }
2.静态Runnable,避免对外部类引用
private static final Runnable sRunnable = new Runnable() { @Override publicvoid run() {} }; // Post amessage and delay its execution for 10 minutes. mHandler.postDelayed(sRunnable, 60 * 10 * 1000);
Thread:
1.改为静态内部Thread,而且要在合适的时候结束,不能每次进入activity都起一个Thread
public class MainActivity extends Activity { privateMyThread mThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); exampleThree(); } private void exampleThree() { mThread =new MyThread(); mThread.start(); } /** * Staticinner classes don't hold implicit references to their * enclosingclass, so the Activity instance won't be leaked across *configuration changes. */ private static class MyThread extends Thread { private boolean mRunning = false; @Override public void run() { mRunning= true; while (mRunning) { SystemClock.sleep(1000); } } public void close() { mRunning= false; } } @Override protectedvoid onDestroy() { super.onDestroy(); mThread.close(); } }
时间: 2024-11-09 09:50:34