android开发坑系列一

        一般情况都会认为进程被杀掉之后,Activity里的Fragment也会随之被回收。如果是一般正常的操作流程,“打开Acitivity     ->     Finish Activity”,Activtiy里的Fragment的确会被回收了。
        但是如果使用360手机卫士之类的软件,清理类存(实际上是杀死进程),会发现Fragment并没有被回收,而是一直缓存着。在Activity里的onCreate()方法里,通过FragmentManager.findFragmentByTag()方法来获取Fragment,可以来判断Fragment是否被回收了。

Fragment和Activity正常的生命周期顺序为:
Activity.onCreate()—>Fragment.onCreate()—>Fragment.onCreateView();
但是经过内存清理后,其生命周期顺序都乱套了,变为:
Fragment.onCreate()—>Activity.onCreate()—>Fragment.onCreateView();
可能是Fragment被缓存,在对应的Activity被restore时,其onCreate()会先于父Activity.onCreate()执行了。

     Activity的onCreate()方法里带有一个参数  Bundle savedInstanceState,改参数一般是在Activity被清理后,保存Activity的一些状态数据。一般如果Activity是全新直接启动的,该参数一般为null,但如果Activity是恢复原来状态重新启动的,该参数不为null。特别是用手机内存清理软件之后,Activity都会重新启动,类似恢复现场,并且 savedInstanceState参数不为空,他之前所有的Fragment都会自动重新恢复,所以这里要格外注意。

     在Activity.onCreate()里添加Fragment时,一般得这样:

public class MainActivity extends Activity {
    private ExampleFragment mFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstnaceState);
        // Only add fragment if this is the initial Activity creation
        if (savedInstanceState == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mFragment = new ExampleFragment();
            fragmentTransaction.add(R.id.fragment_container, fragment, "tag");
            fragmentTransaction.commit();
        } else {
            // Don't add the fragment!
            // (and use savedInstanceState to restore Activity state)
           FragmentManager fragmentManager = getFragmentManager();
           mFragment = fragmentManager.findFragmentByTag("tag");  
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值