[英]Android exception when popping backstack
This is a followup question to these questions: popBackStack() after saveInstanceState() Application crashes in background, when popping a fragment from stack 这是这些问题的后续问题: 从堆栈弹出片段时, saveInstanceState()之后的popBackStack() 应用程序在后台崩溃
I am creating an application which uses a service and is reacting to events which are created by the service. 我正在创建一个使用服务的应用程序,并对应用程序创建的事件做出反应。 One of the events is called within a fragment and is popping from the backstack like this:
其中一个事件在一个片段内被调用,并像这样从后台弹出:
getSupportFragmentManager().popBackStack(stringTag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
When the app is in the foreground it works fine. 当应用程序在前台运行时,它可以正常工作。 When the app is in the background, I get an
当应用程序在后台运行时,
IllegalStateException: Can not perform this action after onSaveInstanceState
IllegalStateException:在onSaveInstanceState之后无法执行此操作
I have already tried overriding onSaveInstanceState
with an empty method. 我已经尝试使用空方法覆盖
onSaveInstanceState
。
Why do I get this exception only when the app is in the background and how can I solve it? 为什么仅在应用程序在后台时才出现此异常,我该如何解决?
Try something like this. 尝试这样的事情。
public abstract class PopActivity extends Activity {
private boolean mVisible;
@Override
public void onResume() {
super.onResume();
mVisible = true;
}
@Override
protected void onPause() {
super.onPause();
mVisible = false;
}
private void popFragment() {
if (!mVisible) {
return;
}
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
when you implement the above code alone when you resume the app you will find yourself in a fragment that you actually want to be popped. 当您在恢复应用程序时单独实现上述代码时,您会发现自己实际上是一个要弹出的片段。 You can use the following snipped to fix this issue:
您可以使用以下摘录来解决此问题:
public abstract class PopFragment extends Fragment {
private static final String KEY_IS_POPPED = "KEY_IS_POPPED";
private boolean mPopped;
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(KEY_IS_POPPED, mPopped);
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPopped = savedInstanceState.getBoolean(KEY_IS_POPPED);
}
}
@Override
public void onResume() {
super.onResume();
if (mPopped) {
popFragment();
}
}
protected void popFragment() {
mPopped = true;
// null check and interface check advised
((PopActivity) getActivity()).popFragment();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.