文章參考:http://blog.nimbledroid.com/2016/05/23/memory-leaks.html
http://wetest.QQ.com/lab/view/99.html
實例代碼一: MainActivity:
public class MainActivity extends AppCompatActivity { TextView tv_test; PRivate Handler handler = new MyHandler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_test = (TextView) findViewById(R.id.tv_test); Message message = Message.obtain(); message.what = 0; message.obj = "000"; handler.sendMessageDelayed(message,60000); new Util(this,handler); } @Override protected void onDestroy() { super.onDestroy(); //handler.removeCallbacksAndMessages(null); } class MyHandler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); tv_test.setText((CharSequence) msg.obj); } }}Util代碼:
public class Util { private static Context context; private static Handler handler; Util(Context context,Handler handler){ this.context = context; this.handler = handler; }}由于Util中的context是static的,即其生命周期是和應用一樣長的,在MainActivity方法中創建Util對象的時候,持有了MainActivity的引用(即this),導致該MainActivity無法被垃圾回收器回收,這樣就造成了內存泄漏。
內部類會隱式地持有了外部類。在該例子中,MyHandler會持有MainActivity的引用,而Util中的靜態變量又持有了MyHandler的引用,這樣還是靜態變量間接地持有了Activity,導致Activity無法被垃圾回收器回收。 另外還有其它幾種常見的實例 實例一:TimerTask
private void scheduleTimer() { new Timer().schedule(new TimerTask() { @Override public void run() { while(true); } }, Long.MAX_VALUE >> 1); }實例二:void spawnThread() { new Thread() { @Override public void run() { while(true); } }.start(); }該方法若在Activity中,由于TimerTask使用的是匿名內部類,會持有Activity的引用,因此會造成內存泄漏。其實這個是匿名內部類導致內存泄漏的一個實例。
因為Handler是基于消息的。每次new出Handler,都會創建一個消息隊列用于處理你使用handler發送的消息,形如:handler.send***Message。由于消息的發送總是會有先來后到的區別(如果只是這樣都還好,畢竟再慢也不會太久,總歸可以跑完,可能會延遲個幾秒),但是如果你使用的是sendMessageDelayed(Message msg, long delayMillis)或postDelayed(Runnable r, long delayMillis)等發送延遲消息的時候,那基本內存泄漏發生的概率已經在90%以上了。因為handler會持有MainActivity的引用,會導致MainActivity無法銷毀。
由于View持有其宿主Activity的引用,故和原因一其實是一樣的。
若在OnDestory()中沒有停止動畫,則動畫即時不可見,仍會一直執行下去,tv_test持有Activity的引用,故會導致Activity無法被回收
如有問題,歡迎加群交流:579853893
新聞熱點
疑難解答