我知道有很多与此相关的问题,我已经阅读了很多。这就是为什么我有这样的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWrapperFragment = WrapperFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.layout_content, mWrapperFragment, WrapperFragment.TAG)
.hide(mWrapperFragment)
.commitNow();
}
@Override
protected void onResume() {
super.onResume();
mIsInstanceStateSaved = false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mIsInstanceStateSaved = true;
}
@Override
public void onWebApplicationReady() {
if (shouldShowWrapperWebView()) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, 0)
.show(mWrapperFragment)
.commitNow();
}
}
/**
* Indicates whether the {@code WrapperFragment} instance should be shown or not.
* <p>
* This method will return {@code false} in the following scenarios:
* <ul>
* <li>The {@code WrapperFragment} is already visible to the user.</li>
* <li>The {@link #onSaveInstanceState} method has not yet been called.</li>
* <li>The activity is not in the process of finishing.</li>
* </ul>
*
* @return {@code true} if the {@code WrapperFragment} can be shown, {@code false} otherwise.
*/
private boolean shouldShowWrapperWebView() {
return !mWrapperFragment.isVisible() && !mIsInstanceStateSaved && !isFinishing();
}
这里需要注意的重要一点是onWebApplicationReady
,将由加载在WebView
该WrapperFragment extends WebViewFragment
主机上的 Web 应用程序调用的回调。
鉴于我的shouldShowWrapperWebView()
,我不明白为什么我仍然会收到这个异常,这会使某些用户的应用程序崩溃:
Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(SourceFile:1832)
at android.support.v4.app.FragmentManagerImpl.ensureExecReady(SourceFile:1954)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(SourceFile:1965)
at android.support.v4.app.BackStackRecord.commitNow(SourceFile:614)
at com.companyname.wrapper.WrapperActivity.showWrapperWebView(SourceFile:336)
at com.companyname.wrapper.WrapperActivity.onWebApplicationReady(SourceFile:197)
at com.companyname.wrapper.js.NativeApi$1.run(SourceFile:61)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)