要检查 Android 设备是否有支持自定义标签页的浏览器?

如果您想了解设备上的默认浏览器或任何浏览器是否支持自定义标签页,请使用 CustomTabsClient 中的 getPackageName 帮助程序:

String packageName = CustomTabsClient.getPackageName(
        context, 
        Collections.emptyList()
);
if (packageName == null) {
    // Custom Tabs are not supported by the default browser
}

您还可以检查设备上的任何浏览器是否支持自定义标签页:

// Get all apps that can handle VIEW intents and Custom Tab service connections.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> viewIntentHandlers = packageManager.queryIntentActivities(activityIntent, 0);
// Get a package that supports Custom Tabs
String packageName = CustomTabsClient.getPackageName(
        context, 
        viewIntentHandlers,
        true /* ignore default */
);
if (packageName == null) {
    // Custom Tabs are not supported by any browser on the device
}

Android 11 引入了软件包可见性变更。如果您的 Android 应用以 API 级别 30 或更高级别为目标平台,则需要将以下查询部分添加到 AndroidManifest.xml,否则上述代码段不会返回结果:

<queries>
    <intent>
        <action android:name=
            "android.support.customtabs.action.CustomTabsService" />
    </intent>
</queries>