致命异常:java.lang.IllegalStateException:使用LocalBroadcastManager销毁了Activity

时间:2016-01-06 09:07:04

标签: android

我使用BroadcastReceiverLocalBrodcastManager来跟踪数据更改并更新视图。 代码示例如下:

public class TestActivity extends AppCompatActivity {

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            doSomeStaff();
        }
    };

    private void doSomeStaff() {
        //Do some staff with activity
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver,null);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    }
}

我很少遇到下一次崩溃:

Fatal Exception: java.lang.IllegalStateException: Activity has been destroyed
       at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1470)
       at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
       at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:617)

我认为是因为我在屏幕上有一个googleMap并根据数据状态显示/隐藏它。 例如:

getSupportFragmentManager().beginTransaction()
                    .show(mMapFragment).commitAllowingStateLoss();

1 个答案:

答案 0 :(得分:0)

似乎现在最简单的解决方案是使用isDestroyed()检查来包围onReceive。

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!isDestroyed) {
           doSomeStaff();
        }
    }
};