片段崩溃活动被破坏

时间:2016-09-28 08:08:08

标签: android android-fragments

我在少数设备上面临这种特殊的崩溃

Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:309)
       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run(Thread.java:818)
Caused by java.lang.IllegalStateException: Activity has been destroyed
       at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
       at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
       at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:617)
       at net.trellisys.papertrell.components.mediagallery.MGBaseActivity$initQuickControls.doInBackground(MGBaseActivity.java:136)
       at net.trellisys.papertrell.components.mediagallery.MGBaseActivity$initQuickControls.doInBackground(MGBaseActivity.java:1)
       at android.os.AsyncTask$2.call(AsyncTask.java:295)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run(Thread.java:818)

我正在做的是使用Fragment方法将Activity加载到Async

我无法在我身边重新创建此错误,但在许多设备中已经看到了这个问题。任何人都可以帮我解决这个错误吗?

以下是代码段: -

public class initQuickControls extends AsyncTask<String,Void,String> {
    String fromPage = "";
    public initQuickControls(String from){
        fromPage = from;
    }
     QuickControlsFragment quicFrag = null;
   @Override
   protected String doInBackground(String... strings) {
       quicFrag = new QuickControlsFragment(fromPage);
       FragmentManager fragManager = getSupportFragmentManager();
       fragManager.beginTransaction().replace(R.id.quickcontrols_container,quicFrag).commitAllowingStateLoss();
       return "EXECUTED";
   }

   protected void onPostExecute(String result) {}
}

这就是我调用Fragment的方式: -

new initQuickControls("List").execute("");

1 个答案:

答案 0 :(得分:2)

首先,您应该熟悉activity lifecycle 我认为你的AsynkTask在活动被破坏时完成,这就是你无法执行任何片段事务的原因。您可以在此交易之前添加条件:

if (!MainActivity.this.isFinishing()) {...}

希望它能提供帮助。

但是,如果您仅使用AsynkTask添加片段 - 这是不正确的。只需在onCreate方法中添加您的片段,无需任何其他代码。

修改

您无法在doInBackground方法中执行UI操作,因为它不在UI线程中运行。将特定于Ui的代码移至onPostExecute方法并且它可以正常工作。不要忘记isFinishing()条件。此外,您应该取消所有AsyncTasks Activity.onBackPressed()方法以避免此类问题。