2013-08-01 63 views
1
@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    ((CustomApplication) getApplication()).detach(this);  
} 

在生成PMD報告,我得到這個錯誤的末尾呼籲:中超應在方法結束時調用。通常情況下,您最終會將超級方法保留在頂部(第一條語句),以便其父類首先被初始化。超級應該在方法

+0

因爲它調用保存實例,在主事件結束後如何保存您的個人設置? – deadfish

+2

只對構造函數強制 – Blackbelt

回答

4

Normally you would eventually keep the super method at the top(First Statement) so that its parent class is first called initialized.

以下代碼片段顯示了Activity#onSaveInstanceState(Bundle outState)的外觀。您可以通過調用super.onSaveInstanceState(outState);來看到它只保存了作爲參數傳入的Bundle。因此,在實際保存Bundle內部之前調用超級方法是沒有意義的。

protected void onSaveInstanceState(Bundle outState) { 
    outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState()); 
    Parcelable p = mFragments.saveAllState(); 
    if (p != null) { 
     outState.putParcelable(FRAGMENTS_TAG, p); 
    } 
    getApplication().dispatchActivitySaveInstanceState(this, outState); 
} 
0

根據這一SO,不要緊,你只要鍵不衝突調用它。它們應該是等價的。

So long as your keys do not collide (e.g., ID being the same as something Android uses internally), the two are identical.

但是他這樣說,谷歌的文檔中關於The Activity's Lifecycle顯示了在結尾添加這一點。我仍然會遵循這一點:

// invoked when the activity may be temporarily destroyed, save the instance state here 
@Override 
public void onSaveInstanceState(Bundle outState) { 
    out.putString(GAME_STATE_KEY, mGameState); 
    out.putString(TEXT_VIEW_KEY, mTextView.getText()); 

    // call superclass to save any view hierarchy 
    super.onSaveInstanceState(out); 
}