@Override
  /**
   * When this activity is destroyed, this method removes it from the activity stack, performs clean
   * up, and fires javascript 'destroy' event.
   */
  protected void onDestroy() {
    Log.d(TAG, "Activity " + this + " onDestroy", Log.DEBUG_MODE);

    inForeground = false;
    TiApplication tiApp = getTiApp();
    // Clean up dialogs when activity is destroyed.
    releaseDialogs(true);

    if (tiApp.isRestartPending()) {
      super.onDestroy();
      if (!isFinishing()) {
        finish();
      }
      return;
    }

    synchronized (lifecycleListeners.synchronizedList()) {
      for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
        try {
          TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_DESTROY);

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
        }
      }
    }

    super.onDestroy();

    boolean isFinishing = isFinishing();

    // If the activity is finishing, remove the windowId and supportHelperId so the window and
    // supportHelper can be released.
    // If the activity is forced to destroy by Android OS, keep the windowId and supportHelperId so
    // the activity can be recovered.
    if (isFinishing) {
      int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
      TiActivityWindows.removeWindow(windowId);
      TiActivitySupportHelpers.removeSupportHelper(supportHelperId);
    }

    fireOnDestroy();

    if (layout instanceof TiCompositeLayout) {
      Log.e(TAG, "Layout cleanup.", Log.DEBUG_MODE);
      ((TiCompositeLayout) layout).removeAllViews();
    }
    layout = null;

    // LW windows
    if (window == null && view != null) {
      view.releaseViews();
      view = null;
    }

    if (window != null) {
      window.closeFromActivity(isFinishing);
      window = null;
    }

    if (menuHelper != null) {
      menuHelper.destroy();
      menuHelper = null;
    }

    if (activityProxy != null) {
      activityProxy.release();
      activityProxy = null;
    }

    // Don't dispose the runtime if the activity is forced to destroy by Android,
    // so we can recover the activity later.
    KrollRuntime.decrementActivityRefCount(isFinishing);
    KrollRuntime.suggestGC();
  }