檢查 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>