java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
异常出现的原因:在Activity的状态保存之后,调用FragmentTransaction的commit(),因此可能会造成Activity state loss (Activity状态丢失)的现象。在我们深入了解它之前,首先看一下onSaveInstanceState()这个方法。由于Android应用程序并不能控制其自身的生命周期,其生命周期由Android系统根据用户操作、系统状态等来控制,Android系统可以决定终止某个进程(应用程序)来回收内存资源,而处于后台(Background)的应用程序可能会被终止。然而作为用户,当其在对App1进行了某些操作(比如输入文字)之后,切换到了App2,此时如果Android系统决定终止App1,而之前输入的内容没有被保存下来的话,就会造成用户信息的丢失,这是一种不好的用户体验。为了让Android系统对应用程序的管理对用户透明,在应用程序被(自愿)回收之前,可以在onSaveInstanceState()方法中保存其当前Activity的状态。这种情况下,就算App1被Android系统终止,当下次用户再打开此Activity之后,这些被保存的状态也可以重新加载,这样Ativity是否被Android系统回收对于用户来说就没有区别了,切换效果会和App1在foreground和background状态切换一样。
Dispatch onResume() to fragments. Note that for better inter-operation with older versions of the platform, at the point of this call the fragments attached to the activity are not resumed. This means that in some cases the previous state may still be saved, not allowing fragment transactions that modify the state. To correctly interact with fragments in their proper state, you should instead override onResumeFragments().
privateboolean mReturningWithResult =false;@Overrideprotectedvoid onActivityResult(int requestCode,int resultCode,Intent data){super.onActivityResult(requestCode, resultCode, data);
mReturningWithResult =true;}@Overrideprotectedvoid onPostResume(){super.onPostResume();if(mReturningWithResult){// Commit your transactions here.}// Reset the boolean flag back to false for next time.
mReturningWithResult =false;}