標籤:
轉自:Android中使用Handler引發的記憶體泄露
在Activity中,經常會用到自訂的Handler來處理主線程收到的Message,但是ADT20以後,直接定義的如下定義的內部會有提示說這種使用方法有記憶體流失的風險:
private Handler mHandle = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: // this is the code break; default: break; } super.handleMessage(msg); } };
當使用Android lint工具的話,會得到這樣的警告,具體的提示如下:
This Handler class should be static or leaks might occur (com.example.multifragment.SampleActivity.1) Issue: Ensures that Handler classes do not hold on to a reference to an outer class Id: HandlerLeak Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.
1.當一個Android應用啟動的時候,會自動建立一個供應用主線程使用的Looper執行個體。Looper的主要工作就是一個一個處理訊息佇列中的訊息對象。在Android中,所有Android架構的事件(比如Activity的生命週期方法調用和按鈕點擊等)都是放入到訊息中,然後加入到Looper要處理的訊息佇列中,由Looper負責一條一條地進行處理。主線程中的Looper生命週期和當前應用一樣長。
2.當一個Handler在主線程進行了初始化之後,我們發送一個target為這個Handler的訊息到Looper處理的訊息佇列時,實際上已經發送的訊息已經包含了一個Handler執行個體的引用,只有這樣Looper在處理到這條訊息時才可以調用Handler#handleMessage(Message)完成訊息的正確處理。
3.在Java中,非靜態內部類和匿名內部類都會隱式地持有其外部類的引用。靜態內部類不會持有外部類的引用。
下面的例子:
public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Handler() { @Override public void handleMessage(Message msg) { // ... } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Post a message and delay its execution for 10 minutes. mLeakyHandler.postDelayed(new Runnable() { @Override public void run() { /* ... */ } }, 1000 * 60 * 10); // Go back to the previous Activity. finish(); }}
分析一下上面的代碼,當我們執行了Activity的finish方法,被延遲的訊息會在被處理之前存在於主線程訊息佇列中10分鐘,而這個訊息中又包含了Handler的引用,而Handler是一個匿名內部類的執行個體,其持有外面的SampleActivity的引用,所以這導致了SampleActivity無法回收,進行導致SampleActivity持有的很多資源都無法回收,這就是我們常說的記憶體泄露。
注意上面的new Runnable這裡也是匿名內部類實現的,同樣也會持有SampleActivity的引用,也會阻止SampleActivity被回收。
要解決這種問題,思路就是不適用非靜態內部類,繼承Handler時,要麼是放在單獨的類檔案中,要麼就是使用靜態內部類。因為靜態內部類不會持有外部類的引用,所以不會導致外部類執行個體的記憶體泄露。當你需要在靜態內部類中調用外部的Activity時,我們可以使用弱引用來處理。另外關於同樣也需要將Runnable設定為靜態成員屬性。注意:一個靜態匿名內部類執行個體不會持有外部類的引用。 修改後不會導致記憶體泄露的代碼如下
public class SampleActivity extends Activity { /** * Instances of static inner classes do not hold an implicit * reference to their outer class. */ private static class MyHandler extends Handler { private final WeakReference<sampleactivity> mActivity; public MyHandler(SampleActivity activity) { mActivity = new WeakReference<sampleactivity>(activity); } @Override public void handleMessage(Message msg) { SampleActivity activity = mActivity.get(); if (activity != null) { // ... } } } private final MyHandler mHandler = new MyHandler(this); /** * Instances of anonymous classes do not hold an implicit * reference to their outer class when they are static. */ private static final Runnable sRunnable = new Runnable() { @Override public void run() { /* ... */ } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Post a message and delay its execution for 10 minutes. mHandler.postDelayed(sRunnable, 1000 * 60 * 10); // Go back to the previous Activity. finish(); }}
其實在Android中很多的記憶體泄露都是由於在Activity中使用了非靜態內部類導致的,就像本文提到的一樣,所以當我們使用時要非靜態內部類時要格外注意,如果其執行個體的持有對象的生命週期大於其外部類對象,那麼就有可能導致記憶體泄露。傾向於使用文章的靜態類和弱引用的方法解決這種問題。
除了上述弱引用的方法,其他解決方案:@SuppressLint("HandlerLeak")應用問題
第一種:(不推薦)根據提示,直接加入“@SuppressLint("HandlerLeak")”的注釋或者在Lint Error Checking裡面檢索HandlerLeak,然後選擇ignore。不推薦,這種方法實際上沒有解決問題。
第二種 :把Handler定義成static,然後用post方法把Runnable對象傳送到主線程,這種方法將要發送的訊息轉換成了對應的Runable對象,適用於只有一個訊息要發送的情形,如果有多個訊息要發送可以採用上述弱引用的方法。
Android Handler Leak