1. 程式人生 > >Android O TextView記憶體洩漏

Android O TextView記憶體洩漏

最近在版本迭代過程中遇到一個奇怪的記憶體洩漏問題,用mat開啟hprof檔案後,看到Activity例項還存在,檢視其gc root後,是這樣的結果: 在這裡插入圖片描述 可以看到是因為AsycTask引用了TextView,然後引用了EditText再引用了mContext,其中EditText是自己程式碼裡的用的控制元件,Calculator是一個Acitivity,奇怪的問題是程式碼裡面沒有任何在AsyncTask裡使用EditText或者TextView的地方,為了排除問題,我把所有可能的handler使用和listener都去掉了,但最後還是有這個問題,於是懷疑是TextView本身的問題,於是檢視TextView原始碼,有可能是其內部使用了AsyncTask,果然,在TextView碼源裡發現這樣一段程式碼:

    private void updateTextServicesLocaleAsync() {
        // AsyncTask.execute() uses a serial executor which means we don't have
        // to lock around updateTextServicesLocaleLocked() to prevent it from
        // being executed n times in parallel.
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                updateTextServicesLocaleLocked();
            }
        });
    }

updateTextServicesLocaleAsync函式裡面使用了AsyncTask執行了個runnable,因此這裡引用到了TextView,因為這個洩漏發生在api內部,因此沒法只能google或者廠商解決〜