org.chromium.chrome.browser.WarmupManager Java Examples

The following examples show how to use org.chromium.chrome.browser.WarmupManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 6 votes vote down vote up
/** Warmup activities that should only happen once. */
@SuppressFBWarnings("DM_EXIT")
private static void initializeBrowser(final Application app) {
    ThreadUtils.assertOnUiThread();
    try {
        ChromeBrowserInitializer.getInstance(app).handleSynchronousStartup();
    } catch (ProcessInitException e) {
        Log.e(TAG, "ProcessInitException while starting the browser process.");
        // Cannot do anything without the native library, and cannot show a
        // dialog to the user.
        System.exit(-1);
    }
    final Context context = app.getApplicationContext();
    final ChromeApplication chrome = (ChromeApplication) context;
    ChildProcessCreationParams.set(chrome.getChildProcessCreationParams());
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ChildProcessLauncher.warmUp(context);
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    ChromeBrowserInitializer.initNetworkChangeNotifier(context);
    WarmupManager.getInstance().initializeViewHierarchy(
            context, R.layout.custom_tabs_control_container);
}
 
Example #2
Source File: CustomTabActivity.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Finishes the activity and removes the reference from the Android recents.
 *
 * @param reparenting true iff the activity finishes due to tab reparenting.
 */
public final void finishAndClose(boolean reparenting) {
    if (mIsClosing) return;
    mIsClosing = true;
    if (!reparenting) {
        // Closing the activity destroys the renderer as well. Re-create a spare renderer some
        // time after, so that we have one ready for the next tab open. This does not increase
        // memory consumption, as the current renderer goes away. We create a renderer as a lot
        // of users open several Custom Tabs in a row. The delay is there to avoid jank in the
        // transition animation when closing the tab.
        ThreadUtils.postOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                WarmupManager.getInstance().createSpareWebContents();
            }
        }, 500);
    }

    handleFinishAndClose();
}
 
Example #3
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private boolean preconnectUrls(List<Bundle> likelyBundles) {
    boolean atLeastOneUrl = false;
    if (likelyBundles == null) return false;
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    for (Bundle bundle : likelyBundles) {
        Uri uri;
        try {
            uri = IntentUtils.safeGetParcelable(bundle, CustomTabsService.KEY_URL);
        } catch (ClassCastException e) {
            continue;
        }
        String url = checkAndConvertUri(uri);
        if (url != null) {
            warmupManager.maybePreconnectUrlAndSubResources(profile, url);
            atLeastOneUrl = true;
        }
    }
    return atLeastOneUrl;
}
 
Example #4
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Warmup activities that should only happen once. */
@SuppressFBWarnings("DM_EXIT")
private static void initializeBrowser(final Application app) {
    ThreadUtils.assertOnUiThread();
    try {
        ChromeBrowserInitializer.getInstance(app).handleSynchronousStartupWithGpuWarmUp();
    } catch (ProcessInitException e) {
        Log.e(TAG, "ProcessInitException while starting the browser process.");
        // Cannot do anything without the native library, and cannot show a
        // dialog to the user.
        System.exit(-1);
    }
    final Context context = app.getApplicationContext();
    ChildProcessLauncher.warmUp(context);
    ChromeBrowserInitializer.initNetworkChangeNotifier(context);
    WarmupManager.getInstance().initializeViewHierarchy(
            context, R.layout.custom_tabs_control_container, R.layout.custom_tabs_toolbar);
}
 
Example #5
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Finishes the activity and removes the reference from the Android recents.
 *
 * @param reparenting true iff the activity finishes due to tab reparenting.
 */
public final void finishAndClose(boolean reparenting) {
    mIsClosing = true;
    if (!reparenting) {
        // Closing the activity destroys the renderer as well. Re-create a spare renderer some
        // time after, so that we have one ready for the next tab open. This does not increase
        // memory consumption, as the current renderer goes away. We create a renderer as a lot
        // of users open several Custom Tabs in a row. The delay is there to avoid jank in the
        // transition animation when closing the tab.
        ThreadUtils.postOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                WarmupManager.getInstance().createSpareWebContents();
            }
        }, 500);
    }

    handleFinishAndClose();
}
 
Example #6
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
private boolean preconnectUrls(List<Bundle> likelyBundles) {
    boolean atLeastOneUrl = false;
    if (likelyBundles == null) return false;
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    for (Bundle bundle : likelyBundles) {
        Uri uri;
        try {
            uri = IntentUtils.safeGetParcelable(bundle, CustomTabsService.KEY_URL);
        } catch (ClassCastException e) {
            continue;
        }
        String url = checkAndConvertUri(uri);
        if (url != null) {
            warmupManager.maybePreconnectUrlAndSubResources(profile, url);
            atLeastOneUrl = true;
        }
    }
    return atLeastOneUrl;
}
 
Example #7
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * High confidence mayLaunchUrl() call, that is:
 * - Tries to prerender if possible.
 * - An empty URL cancels the current prerender if any.
 * - If prerendering is not possible, makes sure that there is a spare renderer.
 */
private void highConfidenceMayLaunchUrl(CustomTabsSessionToken session,
        int uid, String url, Bundle extras, List<Bundle> otherLikelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (TextUtils.isEmpty(url)) {
        cancelPrerender(session);
        return;
    }
    url = DataReductionProxySettings.getInstance().maybeRewriteWebliteUrl(url);
    boolean noPrerendering =
            extras != null ? extras.getBoolean(NO_PRERENDERING_KEY, false) : false;
    WarmupManager.getInstance().maybePreconnectUrlAndSubResources(
            Profile.getLastUsedProfile(), url);
    boolean didStartPrerender = false;
    if (!noPrerendering && mayPrerender(session)) {
        didStartPrerender = prerenderUrl(session, url, extras, uid);
    }
    preconnectUrls(otherLikelyBundles);
    if (!didStartPrerender) createSpareWebContents();
}
 
Example #8
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 6 votes vote down vote up
private boolean preconnectUrls(List<Bundle> likelyBundles) {
    boolean atLeastOneUrl = false;
    if (likelyBundles == null) return false;
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    for (Bundle bundle : likelyBundles) {
        Uri uri;
        try {
            uri = IntentUtils.safeGetParcelable(bundle, CustomTabsService.KEY_URL);
        } catch (ClassCastException e) {
            continue;
        }
        String url = checkAndConvertUri(uri);
        if (url != null) {
            warmupManager.maybePreconnectUrlAndSubResources(profile, url);
            atLeastOneUrl = true;
        }
    }
    return atLeastOneUrl;
}
 
Example #9
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/** Warmup activities that should only happen once. */
@SuppressFBWarnings("DM_EXIT")
private static void initializeBrowser(final Application app) {
    ThreadUtils.assertOnUiThread();
    try {
        ChromeBrowserInitializer.getInstance(app).handleSynchronousStartup();
    } catch (ProcessInitException e) {
        Log.e(TAG, "ProcessInitException while starting the browser process.");
        // Cannot do anything without the native library, and cannot show a
        // dialog to the user.
        System.exit(-1);
    }
    final Context context = app.getApplicationContext();
    final ChromeApplication chrome = (ChromeApplication) context;
    ChildProcessCreationParams.set(chrome.getChildProcessCreationParams());
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ChildProcessLauncher.warmUp(context);
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    ChromeBrowserInitializer.initNetworkChangeNotifier(context);
    WarmupManager.getInstance().initializeViewHierarchy(
            context, R.layout.custom_tabs_control_container, R.layout.custom_tabs_toolbar);
}
 
Example #10
Source File: AsyncInitializationActivity.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void maybePreconnect() {
    TraceEvent.begin("maybePreconnect");
    Intent intent = getIntent();
    if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        final String url = intent.getDataString();
        WarmupManager.getInstance()
            .maybePreconnectUrlAndSubResources(Profile.getLastUsedProfile(), url);
    }
    TraceEvent.end("maybePreconnect");
}
 
Example #11
Source File: ChromeLauncherActivity.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/** When started with an intent, maybe pre-resolve the domain. */
private void maybePrefetchDnsInBackground() {
    if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        String maybeUrl = IntentHandler.getUrlFromIntent(getIntent());
        if (maybeUrl != null) {
            WarmupManager.getInstance().maybePrefetchDnsForUrlInBackground(this, maybeUrl);
        }
    }
}
 
Example #12
Source File: AsyncInitializationActivity.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void maybePreconnect() {
    TraceEvent.begin("maybePreconnect");
    Intent intent = getIntent();
    if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        final String url = intent.getDataString();
        WarmupManager.getInstance()
            .maybePreconnectUrlAndSubResources(Profile.getLastUsedProfile(), url);
    }
    TraceEvent.end("maybePreconnect");
}
 
Example #13
Source File: CustomTabActivity.java    From 365browser with Apache License 2.0 5 votes vote down vote up
private Tab createMainTab() {
    CustomTabsConnection connection = CustomTabsConnection.getInstance(getApplication());
    String url = getUrlToLoad();
    String referrerUrl = connection.getReferrer(mSession, getIntent());
    Tab tab = new Tab(Tab.INVALID_TAB_ID, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(),
            TabLaunchType.FROM_EXTERNAL_APP, null, null);
    tab.setAppAssociatedWith(connection.getClientPackageNameForSession(mSession));

    int webContentsStateOnLaunch = WEBCONTENTS_STATE_NO_WEBCONTENTS;
    WebContents webContents = connection.takePrerenderedUrl(mSession, url, referrerUrl);
    mUsingPrerender = webContents != null;
    if (mUsingPrerender) webContentsStateOnLaunch = WEBCONTENTS_STATE_PRERENDERED_WEBCONTENTS;
    if (!mUsingPrerender) {
        webContents = WarmupManager.getInstance().takeSpareWebContents(false, false);
        if (webContents != null) webContentsStateOnLaunch = WEBCONTENTS_STATE_SPARE_WEBCONTENTS;
    }
    RecordHistogram.recordEnumeratedHistogram("CustomTabs.WebContentsStateOnLaunch",
            webContentsStateOnLaunch, WEBCONTENTS_STATE_MAX);
    if (webContents == null) {
        webContents = WebContentsFactory.createWebContentsWithWarmRenderer(false, false);
    }
    if (!mUsingPrerender) {
        connection.resetPostMessageHandlerForSession(mSession, webContents);
    }
    tab.initialize(
            webContents, getTabContentManager(),
            new CustomTabDelegateFactory(
                    mIntentDataProvider.shouldEnableUrlBarHiding(),
                    mIntentDataProvider.isOpenedByChrome(),
                    getFullscreenManager().getBrowserVisibilityDelegate()),
            false, false);

    if (mIntentDataProvider.shouldEnableEmbeddedMediaExperience()) {
        tab.enableEmbeddedMediaExperience(true);
    }

    initializeMainTab(tab);
    return tab;
}
 
Example #14
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 5 votes vote down vote up
private void startSpeculation(CustomTabsSessionToken session, String url, int speculationMode,
        Bundle extras, int uid) {
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    boolean preconnect = true, createSpareWebContents = true;
    if (speculationMode == SpeculationParams.HIDDEN_TAB
            && !ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_BACKGROUND_TAB)) {
        speculationMode = SpeculationParams.PRERENDER;
    }
    switch (speculationMode) {
        case SpeculationParams.PREFETCH:
            boolean didPrefetch = new LoadingPredictor(profile).prepareForPageLoad(url);
            if (didPrefetch) mSpeculation = SpeculationParams.forPrefetch(session, url);
            preconnect = !didPrefetch;
            break;
        case SpeculationParams.PRERENDER:
            boolean didPrerender = prerenderUrl(session, url, extras, uid);
            createSpareWebContents = !didPrerender;
            break;
        case SpeculationParams.HIDDEN_TAB:
            launchUrlInHiddenTab(session, url, extras);
            break;
        default:
            break;
    }
    if (preconnect) warmupManager.maybePreconnectUrlAndSubResources(profile, url);
    if (createSpareWebContents) warmupManager.createSpareWebContents();
}
 
Example #15
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Low confidence mayLaunchUrl() call, that is:
 * - Preconnects to the ordered list of URLs.
 * - Makes sure that there is a spare renderer.
 */
@VisibleForTesting
boolean lowConfidenceMayLaunchUrl(List<Bundle> likelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (!preconnectUrls(likelyBundles)) return false;
    WarmupManager.getInstance().createSpareWebContents();
    return true;
}
 
Example #16
Source File: ChromeLauncherActivity.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** When started with an intent, maybe pre-resolve the domain. */
private void maybePrefetchDnsInBackground() {
    if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        String maybeUrl = IntentHandler.getUrlFromIntent(getIntent());
        if (maybeUrl != null) {
            WarmupManager.getInstance().maybePrefetchDnsForUrlInBackground(this, maybeUrl);
        }
    }
}
 
Example #17
Source File: ChromeLauncherActivity.java    From delion with Apache License 2.0 5 votes vote down vote up
/** When started with an intent, maybe pre-resolve the domain. */
private void maybePrefetchDnsInBackground() {
    if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        String maybeUrl = IntentHandler.getUrlFromIntent(getIntent());
        if (maybeUrl != null) {
            WarmupManager.getInstance().maybePrefetchDnsForUrlInBackground(this, maybeUrl);
        }
    }
}
 
Example #18
Source File: AsyncInitializationActivity.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void maybePreconnect() {
    TraceEvent.begin("maybePreconnect");
    Intent intent = getIntent();
    if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        final String url = intent.getDataString();
        WarmupManager.getInstance()
            .maybePreconnectUrlAndSubResources(Profile.getLastUsedProfile(), url);
    }
    TraceEvent.end("maybePreconnect");
}
 
Example #19
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Low confidence mayLaunchUrl() call, that is:
 * - Preconnects to the ordered list of URLs.
 * - Makes sure that there is a spare renderer.
 */
@VisibleForTesting
boolean lowConfidenceMayLaunchUrl(List<Bundle> likelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (!preconnectUrls(likelyBundles)) return false;
    WarmupManager.getInstance().createSpareWebContents();
    return true;
}
 
Example #20
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * High confidence mayLaunchUrl() call, that is:
 * - Tries to prerender if possible.
 * - An empty URL cancels the current prerender if any.
 * - If prerendering is not possible, makes sure that there is a spare renderer.
 */
private void highConfidenceMayLaunchUrl(CustomTabsSessionToken session,
        int uid, String url, Bundle extras, List<Bundle> otherLikelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (TextUtils.isEmpty(url)) {
        cancelPrerender(session);
        return;
    }

    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();

    url = DataReductionProxySettings.getInstance().maybeRewriteWebliteUrl(url);
    int debugOverrideValue = NO_OVERRIDE;
    if (extras != null) debugOverrideValue = extras.getInt(DEBUG_OVERRIDE_KEY, NO_OVERRIDE);

    boolean didStartPrerender = false, didStartPrefetch = false;
    boolean mayPrerender = mayPrerender(session);
    if (mayPrerender) {
        if (debugOverrideValue == PREFETCH_ONLY) {
            didStartPrefetch = new ResourcePrefetchPredictor(profile).startPrefetching(url);
            if (didStartPrefetch) mSpeculation = SpeculationParams.forPrefetch(session, url);
        } else if (debugOverrideValue != NO_PRERENDERING) {
            didStartPrerender = prerenderUrl(session, url, extras, uid);
        }
    }
    preconnectUrls(otherLikelyBundles);
    if (!didStartPrefetch) warmupManager.maybePreconnectUrlAndSubResources(profile, url);
    if (!didStartPrerender) warmupManager.createSpareWebContents();
}
 
Example #21
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Starts as much as possible in anticipation of a future navigation.
 *
 * @param mayCreatesparewebcontents true if warmup() can create a spare renderer.
 * @return true for success.
 */
private boolean warmupInternal(final boolean mayCreateSpareWebContents) {
    // Here and in mayLaunchUrl(), don't do expensive work for background applications.
    if (!isCallerForegroundOrSelf()) return false;
    mClientManager.recordUidHasCalledWarmup(Binder.getCallingUid());
    final boolean initialized = !mWarmupHasBeenCalled.compareAndSet(false, true);
    final int uid = Binder.getCallingUid();
    // The call is non-blocking and this must execute on the UI thread, post a task.
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (!initialized) initializeBrowser(mApplication);
            if (mayCreateSpareWebContents && mSpeculation == null
                    && !SysUtils.isLowEndDevice()) {
                WarmupManager.getInstance().createSpareWebContents();
                // The throttling database uses shared preferences, that can cause a StrictMode
                // violation on the first access. Make sure that this access is not in
                // mayLauchUrl.
                RequestThrottler.getForUid(mApplication, uid);

                Profile profile = Profile.getLastUsedProfile();
                new ResourcePrefetchPredictor(profile).startInitialization();
            }
            mWarmupHasBeenFinished.set(true);
        }
    });
    return true;
}
 
Example #22
Source File: Tab.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes {@link Tab} with {@code webContents}.  If {@code webContents} is {@code null} a
 * new {@link WebContents} will be created for this {@link Tab}.
 * @param webContents       A {@link WebContents} object or {@code null} if one should be
 *                          created.
 * @param tabContentManager A {@link TabContentManager} instance or {@code null} if the web
 *                          content will be managed/displayed manually.
 * @param delegateFactory   The {@link TabDelegateFactory} to be used for delegate creation.
 * @param initiallyHidden   Only used if {@code webContents} is {@code null}.  Determines
 *                          whether or not the newly created {@link WebContents} will be hidden
 *                          or not.
 * @param unfreeze          Whether there should be an attempt to restore state at the end of
 *                          the initialization.
 */
public final void initialize(WebContents webContents, TabContentManager tabContentManager,
        TabDelegateFactory delegateFactory, boolean initiallyHidden, boolean unfreeze) {
    try {
        TraceEvent.begin("Tab.initialize");

        mDelegateFactory = delegateFactory;
        initializeNative();

        RevenueStats.getInstance().tabCreated(this);

        mBrowserControlsVisibilityDelegate =
                mDelegateFactory.createBrowserControlsVisibilityDelegate(this);

        mBlimp = BlimpClientContextFactory
                         .getBlimpClientContextForProfile(
                                 Profile.getLastUsedProfile().getOriginalProfile())
                         .isBlimpEnabled()
                && !mIncognito;

        // Attach the TabContentManager if we have one.  This will bind this Tab's content layer
        // to this manager.
        // TODO(dtrainor): Remove this and move to a pull model instead of pushing the layer.
        attachTabContentManager(tabContentManager);

        // If there is a frozen WebContents state or a pending lazy load, don't create a new
        // WebContents.
        if (getFrozenContentsState() != null || getPendingLoadParams() != null) {
            if (unfreeze) unfreezeContents();
            return;
        }

        if (isBlimpTab() && getBlimpContents() == null) {
            Profile profile = Profile.getLastUsedProfile();
            if (mIncognito) profile = profile.getOffTheRecordProfile();
            mBlimpContents = nativeInitBlimpContents(
                    mNativeTabAndroid, profile, mWindowAndroid.getNativePointer());
            if (mBlimpContents != null) {
                mBlimpContentsObserver = new TabBlimpContentsObserver(this);
                mBlimpContents.addObserver(mBlimpContentsObserver);
            } else {
                mBlimp = false;
            }
        }

        boolean creatingWebContents = webContents == null;
        if (creatingWebContents) {
            webContents = WarmupManager.getInstance().takeSpareWebContents(
                    isIncognito(), initiallyHidden);
            if (webContents == null) {
                webContents =
                        WebContentsFactory.createWebContents(isIncognito(), initiallyHidden);
            }
        }

        ContentViewCore contentViewCore = ContentViewCore.fromWebContents(webContents);

        if (contentViewCore == null) {
            initContentViewCore(webContents);
        } else {
            setContentViewCore(contentViewCore);
        }

        if (!creatingWebContents && webContents.isLoadingToDifferentDocument()) {
            didStartPageLoad(webContents.getUrl(), false);
        }

        getAppBannerManager().setIsEnabledForTab(mDelegateFactory.canShowAppBanners(this));
    } finally {
        if (mTimestampMillis == INVALID_TIMESTAMP) {
            mTimestampMillis = System.currentTimeMillis();
        }

        TraceEvent.end("Tab.initialize");
    }
}
 
Example #23
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Starts as much as possible in anticipation of a future navigation.
 *
 * @param mayCreatesparewebcontents true if warmup() can create a spare renderer.
 * @return true for success.
 */
private boolean warmupInternal(final boolean mayCreateSpareWebContents) {
    // Here and in mayLaunchUrl(), don't do expensive work for background applications.
    if (!isCallerForegroundOrSelf()) return false;
    mClientManager.recordUidHasCalledWarmup(Binder.getCallingUid());
    final boolean initialized = !mWarmupHasBeenCalled.compareAndSet(false, true);
    final int uid = Binder.getCallingUid();
    // The call is non-blocking and this must execute on the UI thread, post a task.
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                TraceEvent.begin("CustomTabsConnection.warmupInternal");
                // Ordering of actions here:
                // 1. Initializing the browser needs to be done once, and first.
                // 2. Creating a spare renderer takes time, in other threads and processes, so
                //    start it sooner rather than later. Can be done several times.
                // 3. Initializing the LoadingPredictor is done once, and triggers
                //    work on other threads, start it early.
                // 4. RequestThrottler first access has to be done only once.

                // (1)
                if (!initialized) initializeBrowser(mApplication);

                // (2)
                if (mayCreateSpareWebContents && mSpeculation == null
                        && !SysUtils.isLowEndDevice()) {
                    WarmupManager.getInstance().createSpareWebContents();
                }

                if (!initialized) {
                    // (3)
                    Profile profile = Profile.getLastUsedProfile();
                    new LoadingPredictor(profile).startInitialization();

                    // (4)
                    // The throttling database uses shared preferences, that can cause a
                    // StrictMode violation on the first access. Make sure that this access is
                    // not in mayLauchUrl.
                    RequestThrottler.getForUid(mApplication, uid);
                }
            } finally {
                TraceEvent.end("CustomTabsConnection.warmupInternal");
            }
            mWarmupHasBeenFinished.set(true);
        }
    });
    return true;
}
 
Example #24
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private Tab createMainTab() {
    CustomTabsConnection customTabsConnection =
            CustomTabsConnection.getInstance(getApplication());
    String url = getUrlToLoad();
    // Get any referrer that has been explicitly set by the app.
    String referrerUrl = IntentHandler.getReferrerUrlIncludingExtraHeaders(getIntent(), this);
    if (referrerUrl == null) {
        Referrer referrer = customTabsConnection.getReferrerForSession(mSession);
        if (referrer != null) referrerUrl = referrer.getUrl();
    }
    Tab tab = new Tab(TabIdManager.getInstance().generateValidId(Tab.INVALID_TAB_ID),
            Tab.INVALID_TAB_ID, false, this, getWindowAndroid(),
            TabLaunchType.FROM_EXTERNAL_APP, null, null);
    tab.setAppAssociatedWith(customTabsConnection.getClientPackageNameForSession(mSession));

    mPrerenderedUrl = customTabsConnection.getPrerenderedUrl(mSession);
    int webContentsStateOnLaunch = WEBCONTENTS_STATE_NO_WEBCONTENTS;
    WebContents webContents =
            customTabsConnection.takePrerenderedUrl(mSession, url, referrerUrl);
    mHasPrerendered = webContents != null;
    if (mHasPrerendered) webContentsStateOnLaunch = WEBCONTENTS_STATE_PRERENDERED_WEBCONTENTS;
    if (!mHasPrerendered) {
        webContents = WarmupManager.getInstance().takeSpareWebContents(false, false);
        if (webContents != null) webContentsStateOnLaunch = WEBCONTENTS_STATE_SPARE_WEBCONTENTS;
    }
    RecordHistogram.recordEnumeratedHistogram("CustomTabs.WebcontentsStateOnLaunch",
            webContentsStateOnLaunch, WEBCONTENTS_STATE_MAX);
    if (webContents == null) webContents = WebContentsFactory.createWebContents(false, false);
    if (!mHasPrerendered) {
        customTabsConnection.resetPostMessageHandlerForSession(mSession, webContents);
    }
    tab.initialize(
            webContents, getTabContentManager(),
            new CustomTabDelegateFactory(
                    mIntentDataProvider.shouldEnableUrlBarHiding(),
                    mIntentDataProvider.isOpenedByChrome(),
                    getFullscreenManager().getBrowserVisibilityDelegate()),
            false, false);
    initializeMainTab(tab);
    return tab;
}
 
Example #25
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldAllocateChildConnection() {
    return !mHasCreatedTabEarly && !mHasPrerender
            && !WarmupManager.getInstance().hasSpareWebContents();
}
 
Example #26
Source File: CustomTabActivity.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldAllocateChildConnection() {
    return !mHasCreatedTabEarly && !mHasSpeculated
            && !WarmupManager.getInstance().hasSpareWebContents();
}
 
Example #27
Source File: Tab.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes {@link Tab} with {@code webContents}.  If {@code webContents} is {@code null} a
 * new {@link WebContents} will be created for this {@link Tab}.
 * @param webContents       A {@link WebContents} object or {@code null} if one should be
 *                          created.
 * @param tabContentManager A {@link TabContentManager} instance or {@code null} if the web
 *                          content will be managed/displayed manually.
 * @param delegateFactory   The {@link TabDelegateFactory} to be used for delegate creation.
 * @param initiallyHidden   Only used if {@code webContents} is {@code null}.  Determines
 *                          whether or not the newly created {@link WebContents} will be hidden
 *                          or not.
 * @param unfreeze          Whether there should be an attempt to restore state at the end of
 *                          the initialization.
 */
public final void initialize(WebContents webContents, TabContentManager tabContentManager,
        TabDelegateFactory delegateFactory, boolean initiallyHidden, boolean unfreeze) {
    try {
        TraceEvent.begin("Tab.initialize");

        mDelegateFactory = delegateFactory;
        initializeNative();

        RevenueStats.getInstance().tabCreated(this);

        mBrowserControlsVisibilityDelegate =
                mDelegateFactory.createBrowserControlsVisibilityDelegate(this);

        // Attach the TabContentManager if we have one.  This will bind this Tab's content layer
        // to this manager.
        // TODO(dtrainor): Remove this and move to a pull model instead of pushing the layer.
        attachTabContentManager(tabContentManager);

        // If there is a frozen WebContents state or a pending lazy load, don't create a new
        // WebContents.
        if (getFrozenContentsState() != null || getPendingLoadParams() != null) {
            if (unfreeze) unfreezeContents();
            return;
        }

        boolean creatingWebContents = webContents == null;
        if (creatingWebContents) {
            webContents = WarmupManager.getInstance().takeSpareWebContents(
                    isIncognito(), initiallyHidden);
            if (webContents == null) {
                webContents =
                        WebContentsFactory.createWebContents(isIncognito(), initiallyHidden);
            }
        }

        ContentViewCore contentViewCore = ContentViewCore.fromWebContents(webContents);

        if (contentViewCore == null) {
            initContentViewCore(webContents);
        } else {
            setContentViewCore(contentViewCore);
        }

        mContentViewCore.addImeEventObserver(new ImeEventObserver() {
            @Override
            public void onImeEvent() {
                // Some text was set in the page. Don't reuse it if a tab is
                // open from the same external application, we might lose some
                // user data.
                mAppAssociatedWith = null;
            }

            @Override
            public void onNodeAttributeUpdated(boolean editable, boolean password) {
                if (getFullscreenManager() == null) return;
                updateFullscreenEnabledState();
            }
        });

        if (!creatingWebContents && webContents.isLoadingToDifferentDocument()) {
            didStartPageLoad(webContents.getUrl(), false);
        }

        getAppBannerManager().setIsEnabledForTab(mDelegateFactory.canShowAppBanners(this));
    } finally {
        if (mTimestampMillis == INVALID_TIMESTAMP) {
            mTimestampMillis = System.currentTimeMillis();
        }

        TraceEvent.end("Tab.initialize");
    }
}