/**
   * Creates an instance of {@link EnhancedBookmarkManager}. It also initializes resources, bookmark
   * models and jni bridges.
   *
   * @param activity The activity context to use.
   */
  public EnhancedBookmarkManager(Activity activity) {
    mActivity = activity;
    mEnhancedBookmarksModel = new EnhancedBookmarksModel();
    mMainView = (ViewGroup) mActivity.getLayoutInflater().inflate(R.layout.eb_main, null);
    mDrawer = (DrawerLayout) mMainView.findViewById(R.id.eb_drawer_layout);
    mDrawerListView = (EnhancedBookmarkDrawerListView) mMainView.findViewById(R.id.eb_drawer_list);
    mContentView = (EnhancedBookmarkContentView) mMainView.findViewById(R.id.eb_content_view);
    mViewSwitcher = (ViewSwitcher) mMainView.findViewById(R.id.eb_view_switcher);
    mUndoController =
        new EnhancedBookmarkUndoController(
            activity,
            mEnhancedBookmarksModel,
            ((SnackbarManageable) activity).getSnackbarManager());
    mSearchView = (EnhancedBookmarkSearchView) getView().findViewById(R.id.eb_search_view);
    mEnhancedBookmarksModel.addObserver(mBookmarkModelObserver);
    initializeIfBookmarkModelLoaded();

    // Load partner bookmarks explicitly. We load partner bookmarks in the deferred startup
    // code, but that might be executed much later. Especially on L, showing loading
    // progress bar blocks that so it won't be loaded. http://crbug.com/429383
    PartnerBookmarksShim.kickOffReading(activity);

    mLargeIconBridge = new LargeIconBridge(Profile.getLastUsedProfile().getOriginalProfile());
    ActivityManager activityManager =
        ((ActivityManager)
            ApplicationStatus.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE));
    int maxSize =
        Math.min(activityManager.getMemoryClass() / 4 * 1024 * 1024, FAVICON_MAX_CACHE_SIZE_BYTES);
    mLargeIconBridge.createCache(maxSize);
  }
  /**
   * Handle application level deferred startup tasks that can be lazily done after all the necessary
   * initialization has been completed. Any calls requiring network access should probably go here.
   */
  @UiThread
  public void onDeferredStartupForApp() {
    if (mDeferredStartupComplete) return;
    ThreadUtils.assertOnUiThread();

    long startDeferredStartupTime = SystemClock.uptimeMillis();

    RecordHistogram.recordLongTimesHistogram(
        "UMA.Debug.EnableCrashUpload.DeferredStartUptime",
        startDeferredStartupTime - UmaUtils.getMainEntryPointTime(),
        TimeUnit.MILLISECONDS);
    mLocaleManager.recordStartupMetrics();

    // Punt all tasks that may block the UI thread off onto a background thread.
    new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(Void... params) {
        try {
          TraceEvent.begin("ChromeBrowserInitializer.onDeferredStartup.doInBackground");
          long asyncTaskStartTime = SystemClock.uptimeMillis();
          boolean crashDumpDisabled =
              CommandLine.getInstance().hasSwitch(ChromeSwitches.DISABLE_CRASH_DUMP_UPLOAD);
          if (!crashDumpDisabled) {
            RecordHistogram.recordLongTimesHistogram(
                "UMA.Debug.EnableCrashUpload.Uptime2",
                asyncTaskStartTime - UmaUtils.getMainEntryPointTime(),
                TimeUnit.MILLISECONDS);
            PrivacyPreferencesManager.getInstance().enablePotentialCrashUploading();
            MinidumpUploadService.tryUploadAllCrashDumps(mAppContext);
          }
          CrashFileManager crashFileManager = new CrashFileManager(mAppContext.getCacheDir());
          crashFileManager.cleanOutAllNonFreshMinidumpFiles();

          MinidumpUploadService.storeBreakpadUploadStatsInUma(
              ChromePreferenceManager.getInstance(mAppContext));

          // Force a widget refresh in order to wake up any possible zombie widgets.
          // This is needed to ensure the right behavior when the process is suddenly
          // killed.
          BookmarkWidgetProvider.refreshAllWidgets(mAppContext);

          // Initialize whether or not precaching is enabled.
          PrecacheLauncher.updatePrecachingEnabled(mAppContext);

          if (CommandLine.getInstance().hasSwitch(ChromeSwitches.ENABLE_WEBAPK)) {
            WebApkVersionManager.updateWebApksIfNeeded();
          }

          removeSnapshotDatabase();

          cacheIsChromeDefaultBrowser();

          RecordHistogram.recordLongTimesHistogram(
              "UMA.Debug.EnableCrashUpload.DeferredStartUpDurationAsync",
              SystemClock.uptimeMillis() - asyncTaskStartTime,
              TimeUnit.MILLISECONDS);

          return null;
        } finally {
          TraceEvent.end("ChromeBrowserInitializer.onDeferredStartup.doInBackground");
        }
      }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    AfterStartupTaskUtils.setStartupComplete();

    PartnerBrowserCustomizations.setOnInitializeAsyncFinished(
        new Runnable() {
          @Override
          public void run() {
            String homepageUrl = HomepageManager.getHomepageUri(mAppContext);
            LaunchMetrics.recordHomePageLaunchMetrics(
                HomepageManager.isHomepageEnabled(mAppContext),
                NewTabPage.isNTPUrl(homepageUrl),
                homepageUrl);
          }
        });

    // TODO(aruslan): http://b/6397072 This will be moved elsewhere
    PartnerBookmarksShim.kickOffReading(mAppContext);

    PowerMonitor.create(mAppContext);

    ShareHelper.clearSharedImages(mAppContext);

    // Clear any media notifications that existed when Chrome was last killed.
    MediaCaptureNotificationService.clearMediaNotifications(mAppContext);

    startModerateBindingManagementIfNeeded();

    recordKeyboardLocaleUma();

    ChromeApplication application = (ChromeApplication) mAppContext;
    // Starts syncing with GSA.
    application.createGsaHelper().startSync();

    application.initializeSharedClasses();

    // Start or stop Physical Web
    PhysicalWeb.onChromeStart(application);

    mDeferredStartupComplete = true;

    RecordHistogram.recordLongTimesHistogram(
        "UMA.Debug.EnableCrashUpload.DeferredStartUpDuration",
        SystemClock.uptimeMillis() - startDeferredStartupTime,
        TimeUnit.MILLISECONDS);
  }