无法关闭Handler内的Fragment得到IllegalStateException

时间:2017-06-30 08:25:10

标签: java android android-fragments handler

我试图开始片段并在几秒钟后关闭它,但我收到了错误:

  

java.lang.IllegalStateException:之后无法执行此操作   的onSaveInstanceState

产生异常的代码是:

FragmentManager manager = getSupportFragmentManager();

        fragment = new MediaControlFragment();


        manager.beginTransaction()
                .add(R.id.media_control_frame, fragment)
                .commit();

        handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
            public void run() {
                //do something again
                Log.i(PLAYER_ACTIVITY_TAG, "DESTROYING FRAGMENT");

                manager.beginTransaction().remove(fragment).commit();
                         }
        }, 3500);

现在我在线上发现错误,其中片段应被删除。

有人可以帮助我实现这个目标吗?

编辑:

LOG:

    E/AndroidRuntime: FATAL EXCEPTION: main
Process: PID: 28254
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at aoc.netcast.rs.android_ott_client.activities.PlayerActivity$1.run(PlayerActivity.java:150)
at android.os.Handler.handleCallback(Handler.java:769)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

3 个答案:

答案 0 :(得分:1)

根据您的代码:https://pastebin.com/snbxaGct

您收到此错误是因为您通过调用

调用了HomeActivity
startActivity(new Intent(this, HomeActivity.class));

然后当您从PlayerActivity添加或删除片段时,它会生成错误,因为您切换到了不同的活动HomeActivity

答案 1 :(得分:0)

我尝试了你的代码,这对我来说很好用:

    final FragmentManager manager = getSupportFragmentManager();

    final SomeFragment fragment = new SomeFragment();


    manager.beginTransaction()
            .add(R.id.frame, fragment)
            .commit();
//R.id.frame is frame layout.


    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //do something again
            manager.beginTransaction().remove(fragment).commit();
        }
    }, 3500);

尝试使用"CommitAllowingStateLoss()"代替"commit()"

答案 2 :(得分:0)

你不能从runnable中做到这一点......首先使用getActivity()从片段中获取活动,然后使用活动执行以下操作

activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //your code here which you want to perform in UI   
                }
            });

希望它可以帮到你