2016-01-06 65 views
0

我使用BroadcastReceiverLocalBrodcastManager來跟蹤數據更改和更新視圖。下面 代碼示例:致命異常:java.lang.IllegalStateException:使用LocalBroadcastManager銷燬活動

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(); 
+0

可以檢查活動與['isDetroyed'(http://developer.android.com/reference/android/app/Activity.html#isDestroyed()) – miensol

+0

我知道,根本破壞的問題是爲什麼如果onStop在onDestroy之前進行調用,接收者會被調用 –

回答

0

似乎存在現在的問題是圍繞你的onReceive用isDestroyed()檢查最簡單的解決方案。

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