2019-03-14 15:27:15.832 17656-17656/gch.example.com.testdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: gch.example.com.testdemo, PID: 17656
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:2044)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2067)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:680)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:634)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
at gch.example.com.testdemo.MainActivity$3.run(MainActivity.java:55)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
这个问题出现的原因是,当前Activity已经不再Activity堆栈顶部了,依然要弹出DialogFragment(弹出Dialog没有问题)。
这也就道出了问题的解决办法:在DialogFragment.show() 之前判断当前Activity是否是与用户交互的界面
public static boolean isTopActivy(String cmdName, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(Integer.MAX_VALUE);
String cmpNameTemp = null;
if (null != runningTaskInfos) {
cmpNameTemp = (runningTaskInfos.get(0).topActivity).toString();
}
if (null == cmpNameTemp) {
return false;
}
return cmpNameTemp.equals(cmdName);
}
不好意思,getRunningTasks这个在android L中 deprecated. 那怎么办呢?让用户同意权限吗?别给用户添麻烦了,
使用一个全局变量,判断当前是不是onResume状态把!