首页 > 解决方案 > 无法使用最新的 androidx 浏览器依赖项预热 Chrome CustomTabs

问题描述

我正在寻找一个示例,说明如何在初始化主机应用程序时使用 CustomTabs“预热”功能来预加载 Chrome。有关使用 Chrome CustomTabs 加载 URL 的文档非常不完整,并且所有示例都是 5 年前的,并且使用丑陋的回调机制来实现这一点。

在最新版本(2.2.0)中,我找到了这种看起来很有希望的方法:

     * Connects to the Custom Tabs warmup service, and initializes the browser.
     *
     * This convenience method connects to the service, and immediately warms up the Custom Tabs
     * implementation. Since service connection is asynchronous, the return code is not the return
     * code of warmup.
     * This call is optional, and clients are encouraged to connect to the service, call
     * <code>warmup()</code> and create a session. In this case, calling this method is not
     * necessary.
     *
     * @param context     {@link Context} to use to connect to the remote service.
     * @param packageName Package name of the target implementation.
     * @return Whether the binding was successful.
     */
    public static boolean connectAndInitialize(@NonNull Context context,
            @NonNull String packageName) {
        if (packageName == null) return false;
        final Context applicationContext = context.getApplicationContext();
        CustomTabsServiceConnection connection = new CustomTabsServiceConnection() {
            @Override
            public final void onCustomTabsServiceConnected(
                    @NonNull ComponentName name, @NonNull CustomTabsClient client) {
                client.warmup(0);
                // Unbinding immediately makes the target process "Empty", provided that it is
                // not used by anyone else, and doesn't contain any Activity. This makes it
                // likely to get killed, but is preferable to keeping the connection around.
                applicationContext.unbindService(this);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) { }
        };
        try {
            return bindCustomTabsService(applicationContext, packageName, connection);
        } catch (SecurityException e) {
            return false;
        }
    }

但是预热方法永远不会被调用,性能似乎也没有得到改善。我尝试在 Application 类以及要从中加载 URL 的 Activity 类中调用它。

我正在使用 CustomTabsClient.Builder()..build().launchUrl(url) 加载 URL

标签: androidbrowserandroidx

解决方案


推荐阅读