android - 為什么重復Replace Fragment會內(nèi)存泄漏
問題描述
如圖,當點擊下面的兩個按鈕時,REPALCE上面的Fragmnet,共兩個,反復切換時發(fā)生了內(nèi)存泄漏
這是Fragment的代碼:
public class Fragment2 extends Fragment { private List<Bitmap> lb = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {allocBitMap();allocBitMap();return inflater.inflate(R.layout.f2, container, false); } private void allocBitMap() {Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.men);lb.add(b); } @Override public void onDestroy() {Log.e('onDestroy', 'yes, onDestroy');super.onDestroy(); }}
這是Activity的部分代碼
@Override public void onClick(View v) {switch (v.getId()) { case R.id.bt_left:transFragleft();break; case R.id.bt_right:transFragright();break;} } Fragment f1 = new Fragment1(); Fragment f2 = new Fragment2(); private void transFragleft(){FragmentTransaction ft = getSupportFragmentManager().beginTransaction();ft.replace(R.id.rl_f, f1);ft.commit(); } private void transFragright(){FragmentTransaction ft = getSupportFragmentManager().beginTransaction();ft.replace(R.id.rl_f, f2);ft.commit(); }
這是反復切換時的內(nèi)存狀態(tài):
這是LOGCAT,可以看到onDestroy執(zhí)行了,整個Fragment生命周期馬上就結束了
04-27 09:46:04.682 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy04-27 09:46:06.344 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy04-27 09:46:07.895 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
那么為什么他占用的那塊內(nèi)存還在呢?
提問2:JAVA中怎樣分配一定內(nèi)存,用于實驗,我這種bitmap的方法太LOW了,而且里面還有CONTEXT;
提問3:是否應該避免使用FRAGMENT(我知道用HIDE/SHOW的方式要比REPLACE要好
謝謝!
問題解答
回答1:把LeakCanary集成到代碼里面,看看是什么原因導致的內(nèi)存泄露。而且內(nèi)存圖上升,也不一定就是內(nèi)存泄露。你每次申請了Bitmap,沒準沒達到GC的標準,那內(nèi)存一直上漲也沒問題。
回答2:不是 fragment 的問題,而是你用的bitmap 的原因
相關文章:
1. javascript - 關于定時器 與 防止連續(xù)點擊 問題2. javascript - 求助關于js正則問題3. objective-c - ios百度地圖定位問題4. javascript - 求助這種功能有什么好點的插件?5. javascript - js 有什么優(yōu)雅的辦法實現(xiàn)在同時打開的兩個標簽頁間相互通信?6. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?7. html5 - rudy編譯sass的時候有中文報錯8. html - css 如何添加這種邊框?9. javascript - node.js服務端渲染解疑10. 微信開放平臺 - Android調(diào)用微信分享不顯示
