2016-05-18 30 views
0

首先,我相信這不是一個重複的問題,儘管錯誤的解決方案已經被問了很多次。我嘗試了至少5種不同的解決方案,但他們要麼不改變任何東西,要麼讓事情變得更糟。我想在屏幕鎖定/焦點更改時暫停活動,並允許用戶在應用程序再次打開時取消暫停活動。IllegalStateException在添加片段以響應屏幕鎖定時

public void onWindowFocusChanged(boolean hasFocus) { 
    super.onWindowFocusChanged(hasFocus); 
    if (!hasFocus && pauseFragment == null) { 
     exercisePlayPause(isPaused, workoutExerciseNum); 
     isPaused = !isPaused; 
    } 
} 

exercisePlayPause調用下面的方法

public void PassExerciseNum(int exerciseNum, Boolean isPaused) { 
    if (!isPaused) { 
     pauseFragment = new PauseFragment(); 
     pauseFragment.getExNum(exerciseNum); 
     getFragmentManager().beginTransaction().add(R.id.aworkout_layout, pauseFragment, "pause").commit(); 
    } else { 
     getFragmentManager().beginTransaction().remove(pauseFragment).commit(); 
     pauseFragment = null; 
     exercisePlayPause(true, exerciseNum); 
    } 
} 

當家裏按下按鈕或其他一些應用程序被激活或點擊通知欄這工作得很好。但是,當屏幕被鎖定,然後我得到以下錯誤

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState 
                     at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1411) 
                     at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1429) 
                     at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687) 
                     at android.app.BackStackRecord.commit(BackStackRecord.java:663) 

的違規行爲getFragmentManager().beginTransaction().add(R.id.aworkout_layout。當任何讓用戶離開應用程序的事件時,我正在暫停一些進程。當用戶回到應用程序時,他/她可以從那裏恢復。因此,我並沒有破壞這項活動。我嘗試過使用commitAllowingStateLoss(),但這會讓我失去已暫停進程的數據並變得有點混亂。

因此總之,問題是如何在按下屏幕鎖定按鈕時觸發onSaveInstanceState之前發生fragmenttransaction?

回答

0

該活動的方向爲sensorLandscape。當一個屏幕鎖定它將屏幕轉換爲肖像,當屏幕解鎖時,它將從肖像模式開始,然後變成風景。因此,屏幕鎖定時調用onDestroy。當屏幕解鎖時,onCreate被調用。此方向更改將覆蓋清單中設置的活動方向。當這種有力的方向發生時會發生什麼,可以通過將android:configChanges="orientation|screenSize|keyboardHidden"/>添加到清單來控制。這可以防止調用onDestroy,並且可以獲得「illegalStateException」。