Reference:
http://juniperphoton.net/2017/03/27/jie-jue-viewpager-fragment-de-hui-fu-wen-ti/http://y-anz-m.blogspot.tw/2013/07/viewpager-fragment.html
http://www.voidcn.com/article/p-weicgtjm-kv.html
Issue description:
當Low memory時,process被系統刪除,Activity被銷毀了,但是Fragment還在,導致Fragment重疊,造成開啟app的時間不斷增加使用 adb shell dumpsys activity top 指令
可以發現 fragment數量不停累加
Solution:
在Activity被銷毀前,先將正在使用的fragment object儲存起來下次開啟app後,再將前一次使用的fragment object (現在用不到的) 刪除掉
Code snippet:
@Overrideprotected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Store the current used fragments
if (mFragmentAdapter != null) {
getSupportFragmentManager().putFragment(outState, KEY_FRAG_NAME1, mFragmentAdapter.getFragment(0));
getSupportFragmentManager().putFragment(outState, KEY_FRAG_NAME2, mFragmentAdapter.getFragment(1));
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.................
// Remove previous unused fragments
if (savedInstanceState != null) {
mFragment1 = getSupportFragmentManager().getFragment(savedInstanceState,
KEY_FRAG_NAME1);
mFragment2 = getSupportFragmentManager().getFragment(savedInstanceState,
KEY_FRAG_NAME2);
if(mFragment1 != null || mFragment2 != null){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(mFragment1 );
transaction.remove(mFragment2 );
transaction.commit();
}
}
...............
}
沒有留言:
張貼留言