Android初学者:onDestroy

led*_*edy 6 android destroy android-lifecycle

在覆盖活动的ondestroy时,我应该在super.onDestroy()之前或之后放置命令吗?

protected void onDestroy() {

    //option 1: callback before or ...

    super.onDestroy();

    //option 2: callback after super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)

(现在我担心:如果super.onDestroy太快,它将永远不会到达选项2.)

MBy*_*ByD 7

任何可能与使用活动资源有关的事情都应该在调用之前super.onDestroy().它将达到之后的代码,但如果需要这些资源可能会导致问题.


ian*_*mas 3

这就是当你调用 super.onDestroy(); 时会发生的情况。

安卓源码

protected void onDestroy() {
    mCalled = true;

    // dismiss any dialogs we are managing.
    if (mManagedDialogs != null) {

        final int numDialogs = mManagedDialogs.size();
        for (int i = 0; i < numDialogs; i++) {
            final Dialog dialog = mManagedDialogs.valueAt(i);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    // also dismiss search dialog if showing
    // TODO more generic than just this manager
    SearchManager searchManager = 
        (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchManager.stopSearch();

    // close any cursors we are managing.
    int numCursors = mManagedCursors.size();
    for (int i = 0; i < numCursors; i++) {
        ManagedCursor c = mManagedCursors.get(i);
        if (c != null) {
            c.mCursor.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

本质上,这意味着在代码之前或之后调用它并不重要。