發現了一個問題,ViewPager +FragmentPagerAdapter 的viewpager 的fregment 中獲取getActivity() ,發現有時候會獲取到空的,大概情況是這樣的,第一次打開這個viewpager 所在的activity時是沒有問題的,fregment可以獲取到 getActivity(),然後關掉這個activity也就是finish掉後在進去,debug發現裏面的fregment 中獲取getActivity()竟然變成null 了。。。。原來是FragmentPagerAdapter 會緩存裏面的fregment,,,把activity關掉了但是緩存還在,下次再打開直接掉緩存的。。但是緩存的那個fregment 關聯的activity已經死了。。。導致獲取 getActivity() 爲null
解決方法:
1.用自定的Application 中的定義返回 的Application 當上下文。
public static ClientApp getApplication() {
return mApplication;
}
2.用廣播接收裏面的Context
這個還有個現象是,如果是在裏面的fregment中有Dialog 的話,關掉重新進入,會報android.view.WindowManager$BadTokenException: Unable to add window – token android.os.BinderProxy@19a23757 is not valid ,is your activity running 。意思是你以前的那個activity 已經死了,所以再show這個dialog 的時候要判斷下是否這個activity還活着。