如圖,當(dāng)點(diǎn)擊下面的兩個按鈕時,REPALCE上面的Fragmnet,共兩個,反復(fù)切換時發(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();
}
這是反復(fù)切換時的內(nèi)存狀態(tài):
這是LOGCAT,可以看到onDestroy執(zhí)行了,整個Fragment生命周期馬上就結(jié)束了
04-27 09:46:04.682 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
04-27 09:46:06.344 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
04-27 09:46:07.895 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
那么為什么他占用的那塊內(nèi)存還在呢?
提問2:
JAVA中怎樣分配一定內(nèi)存,用于實(shí)驗(yàn),我這種bitmap的方法太LOW了,而且里面還有CONTEXT;
提問3:
是否應(yīng)該避免使用FRAGMENT(我知道用HIDE/SHOW的方式要比REPLACE要好
謝謝!
把LeakCanary集成到代碼里面,看看是什么原因?qū)е碌膬?nèi)存泄露。
而且內(nèi)存圖上升,也不一定就是內(nèi)存泄露。你每次申請了Bitmap,沒準(zhǔn)沒達(dá)到GC的標(biāo)準(zhǔn),那內(nèi)存一直上漲也沒問題。