androidx.browser.customtabs.CustomTabsService Java Examples

The following examples show how to use androidx.browser.customtabs.CustomTabsService. 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: TwaProviderPicker.java    From android-browser-helper with Apache License 2.0 6 votes vote down vote up
/** Returns a map from package name to LaunchMode for all available Custom Tabs Services. */
private static Map<String, Integer> getLaunchModesForCustomTabsServices(PackageManager pm) {
    List<ResolveInfo> services = pm.queryIntentServices(
            new Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION),
            PackageManager.GET_RESOLVED_FILTER);

    Map<String, Integer> customTabsServices = new HashMap<>();
    for (ResolveInfo service : services) {
        String packageName = service.serviceInfo.packageName;

        if (ChromeLegacyUtils.supportsTrustedWebActivities(pm, packageName)) {
            // Chrome 72-74 support Trusted Web Activites but don't yet have the TWA category on
            // their CustomTabsService.
            customTabsServices.put(packageName, LaunchMode.TRUSTED_WEB_ACTIVITY);
            continue;
        }

        boolean supportsTwas = service.filter != null &&
                service.filter.hasCategory(TRUSTED_WEB_ACTIVITY_CATEGORY);

        customTabsServices.put(packageName,
                supportsTwas ? LaunchMode.TRUSTED_WEB_ACTIVITY : LaunchMode.CUSTOM_TAB);
    }
    return customTabsServices;
}
 
Example #2
Source File: RobolectricUtils.java    From android-browser-helper with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures intents with {@link CustomTabsService#ACTION_CUSTOM_TABS_CONNECTION} resolve to a
 * Service with given categories
 */
public static void installCustomTabsService(String providerPackage, List<String> categories) {
    Intent intent = new Intent()
            .setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION)
            .setPackage(providerPackage);

    IntentFilter filter = new IntentFilter();
    for (String category : categories) {
        filter.addCategory(category);
    }
    ResolveInfo resolveInfo = new ResolveInfo();
    resolveInfo.filter = filter;

    ShadowPackageManager manager = Shadows.shadowOf(RuntimeEnvironment.application
            .getPackageManager());
    manager.addResolveInfoForIntent(intent, resolveInfo);
}
 
Example #3
Source File: UriUtil.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
public static List<Bundle> toCustomTabUriBundle(Uri[] uris, int startIndex) {
    Preconditions.checkArgument(startIndex >= 0, "startIndex must be positive");
    if (uris == null || uris.length <= startIndex) {
        return Collections.emptyList();
    }

    List<Bundle> uriBundles = new ArrayList<>(uris.length - startIndex);
    for (int i = startIndex; i < uris.length; i++) {
        if (uris[i] == null) {
            Logger.warn("Null URI in possibleUris list - ignoring");
            continue;
        }

        Bundle uriBundle = new Bundle();
        uriBundle.putParcelable(CustomTabsService.KEY_URL, uris[i]);
        uriBundles.add(uriBundle);
    }

    return uriBundles;
}
 
Example #4
Source File: ManageDataLauncherActivity.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
private boolean supportsTrustedWebActivities(String providerPackage) {
    if (ChromeLegacyUtils.supportsTrustedWebActivities(getPackageManager(), providerPackage)) {
        return true;
    }
    Intent intent = new Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION)
            .setPackage(providerPackage);
    List<ResolveInfo> services = getPackageManager().queryIntentServices(intent,
            PackageManager.GET_RESOLVED_FILTER);
    if (services.isEmpty()) {
        return false;
    }
    ResolveInfo resolveInfo = services.get(0);
    return resolveInfo.filter != null &&
            resolveInfo.filter.hasCategory(TRUSTED_WEB_ACTIVITY_CATEGORY);
}
 
Example #5
Source File: TwaProviderPickerTest.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
private void installCustomTabsProvider(String packageName) {
    installBrowser(packageName);

    Intent intent = new Intent()
            .setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);

    ResolveInfo resolveInfo = new ResolveInfo();
    resolveInfo.serviceInfo = new ServiceInfo();
    resolveInfo.serviceInfo.packageName = packageName;

    mShadowPackageManager.addResolveInfoForIntent(intent, resolveInfo);
}
 
Example #6
Source File: TwaProviderPickerTest.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
private void installTrustedWebActivityProvider(String packageName) {
    installBrowser(packageName);

    Intent intent = new Intent()
            .setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);

    ResolveInfo resolveInfo = new ResolveInfo();
    resolveInfo.serviceInfo = new ServiceInfo();
    resolveInfo.serviceInfo.packageName = packageName;
    resolveInfo.filter = Mockito.mock(IntentFilter.class);
    when(resolveInfo.filter.hasCategory(eq(TRUSTED_WEB_ACTIVITY_CATEGORY))).thenReturn(true);

    mShadowPackageManager.addResolveInfoForIntent(intent, resolveInfo);
}
 
Example #7
Source File: UriUtilTest.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testToCustomTabUri() {
    Uri exampleUri = Uri.parse("https://www.example.com");
    Uri anotherExampleUri = Uri.parse("https://another.example.com");

    List<Bundle> bundles = UriUtil.toCustomTabUriBundle(
        new Uri[] { exampleUri, anotherExampleUri },
        0);

    assertThat(bundles).hasSize(2);
    assertThat(bundles.get(0).keySet()).contains(CustomTabsService.KEY_URL);
    assertThat(bundles.get(0).get(CustomTabsService.KEY_URL)).isEqualTo(exampleUri);
    assertThat(bundles.get(1).keySet()).contains(CustomTabsService.KEY_URL);
    assertThat(bundles.get(1).get(CustomTabsService.KEY_URL)).isEqualTo(anotherExampleUri);
}
 
Example #8
Source File: UriUtilTest.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testToCustomTabUri_startIndex() {
    Uri anotherExampleUri = Uri.parse("https://another.example.com");

    List<Bundle> bundles = UriUtil.toCustomTabUriBundle(
        new Uri[] {
            Uri.parse("https://www.example.com"),
            anotherExampleUri
        },
        1);

    assertThat(bundles).hasSize(1);
    assertThat(bundles.get(0).keySet()).contains(CustomTabsService.KEY_URL);
    assertThat(bundles.get(0).get(CustomTabsService.KEY_URL)).isEqualTo(anotherExampleUri);
}
 
Example #9
Source File: TestCustomTabsService.java    From android-browser-helper with Apache License 2.0 4 votes vote down vote up
@Override
protected int postMessage(CustomTabsSessionToken sessionToken, String message, Bundle extras) {
    if (!mPostMessageRequested) return CustomTabsService.RESULT_FAILURE_DISALLOWED;
    return CustomTabsService.RESULT_SUCCESS;
}
 
Example #10
Source File: CustomTabManagerTest.java    From AppAuth-Android with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateSession() {
    startBind(true);
    provideClient();

    CustomTabsCallback mockCallbacks = Mockito.mock(CustomTabsCallback.class);
    CustomTabsSession mockSession = Mockito.mock(CustomTabsSession.class);

    Mockito.doReturn(mockSession).when(mClient).newSession(mockCallbacks);

    Uri launchUri1 = Uri.parse("https://idp.example.com");
    Uri launchUri2 = Uri.parse("https://another.example.com");
    Uri launchUri3 = Uri.parse("https://yetanother.example.com");

    Bundle launchUri2Bundle = new Bundle();
    launchUri2Bundle.putParcelable(CustomTabsService.KEY_URL, launchUri2);

    Bundle launchUri3Bundle = new Bundle();
    launchUri3Bundle.putParcelable(CustomTabsService.KEY_URL, launchUri3);

    CustomTabsSession session = mManager.createSession(
        mockCallbacks,
        launchUri1,
        launchUri2,
        launchUri3);

    assertThat(session).isEqualTo(mockSession);

    // upon creation of the session, the code should prime the session with the expected URIs
    @SuppressWarnings("unchecked")
    ArgumentCaptor<List<Bundle>> bundleCaptor = ArgumentCaptor.forClass(List.class);
    Mockito.verify(mockSession).mayLaunchUrl(
        eq(launchUri1),
        eq((Bundle)null),
        bundleCaptor.capture());

    List<Bundle> bundles = bundleCaptor.getValue();
    assertThat(bundles).hasSize(2);
    assertThat(bundles.get(0).get(CustomTabsService.KEY_URL)).isEqualTo(launchUri2);
    assertThat(bundles.get(1).get(CustomTabsService.KEY_URL)).isEqualTo(launchUri3);
}
 
Example #11
Source File: CustomTabsHelper.java    From Easy_xkcd with Apache License 2.0 4 votes vote down vote up
/**
 * Goes through all apps that handle VIEW intents and have a warmup service. Picks
 * the one chosen by the user if there is one, otherwise makes a best effort to return a
 * valid package name.
 *
 * This is <strong>not</strong> threadsafe.
 *
 * @param context {@link Context} to use for accessing {@link PackageManager}.
 * @return The package name recommended to use for connecting to custom tabs related components.
 */
public static String getPackageNameToUse(Context context) {
    if (sPackageNameToUse != null) return sPackageNameToUse;

    PackageManager pm = context.getPackageManager();
    // Get default VIEW intent handler.
    Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
    ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
    String defaultViewHandlerPackageName = null;
    if (defaultViewHandlerInfo != null) {
        defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
    }

    // Get all apps that can handle VIEW intents.
    List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
    List<String> packagesSupportingCustomTabs = new ArrayList<>();
    for (ResolveInfo info : resolvedActivityList) {
        Intent serviceIntent = new Intent();
        serviceIntent.setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);
        serviceIntent.setPackage(info.activityInfo.packageName);
        if (pm.resolveService(serviceIntent, 0) != null) {
            packagesSupportingCustomTabs.add(info.activityInfo.packageName);
        }
    }

    // Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
    // and service calls.
    if (packagesSupportingCustomTabs.isEmpty()) {
        sPackageNameToUse = null;
    } else if (packagesSupportingCustomTabs.size() == 1) {
        sPackageNameToUse = packagesSupportingCustomTabs.get(0);
    } else if (!TextUtils.isEmpty(defaultViewHandlerPackageName)
            && !hasSpecializedHandlerIntents(context, activityIntent)
            && packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
        sPackageNameToUse = defaultViewHandlerPackageName;
    } else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
        sPackageNameToUse = STABLE_PACKAGE;
    } else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
        sPackageNameToUse = BETA_PACKAGE;
    } else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
        sPackageNameToUse = DEV_PACKAGE;
    } else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
        sPackageNameToUse = LOCAL_PACKAGE;
    }
    return sPackageNameToUse;
}
 
Example #12
Source File: SettingsActivity.java    From MaxLock with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    if (MLPreferences.getPreferences(this).getInt(FirstStartActivity.FIRST_START_LAST_VERSION_KEY, 0) != FirstStartActivity.FIRST_START_LATEST_VERSION) {
        startActivity(new Intent(this, FirstStartActivity.class));
    }

    settingsViewModel = ViewModelProviders.of(this).get(SettingsViewModel.class);

    devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
    deviceAdmin = new ComponentName(this, UninstallProtectionReceiver.class);

    setContentView(R.layout.activity_settings);
    contentView = findViewById(R.id.content_view_settings);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    secondFragmentContainer = findViewById(R.id.second_fragment_container);

    Fragment settingsFragment = getSupportFragmentManager().findFragmentByTag(TAG_PREFERENCE_FRAGMENT);
    if (settingsFragment == null || !UNLOCKED) {
        // Main fragment doesn't exist, app just opened
        // → Show lockscreen
        UNLOCKED = false;
        if (!MLPreferences.getPreferences(this).getString(Common.LOCKING_TYPE, "").isEmpty()) {
            contentView.addView(lockscreen = new LockView(this, null), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lockscreen.forceFocus();

            // → Hide Action bar
            toolbar.setTranslationY(-getResources().getDimensionPixelSize(R.dimen.toolbar_height));
        } else UNLOCKED = true;
        // → Create and display settings
        settingsFragment = getIntent().getAction() != null && getIntent().getAction().equals(BuildConfig.APPLICATION_ID + ".VIEW_APPS") ?
                new AppListFragment() : MaxLockPreferenceFragment.Screen.MAIN.getScreen();
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, settingsFragment, TAG_PREFERENCE_FRAGMENT).commit();
    }

    ctConnection = new CustomTabsServiceConnection() {
        @Override
        public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) {
            customTabsClient.warmup(0);
            ctSession = customTabsClient.newSession(new CustomTabsCallback());
            if (ctSession == null)
                return;
            Bundle maxr1998Website = new Bundle();
            maxr1998Website.putParcelable(CustomTabsService.KEY_URL, Common.MAXR1998_URI);
            Bundle technoSparksProfile = new Bundle();
            technoSparksProfile.putParcelable(CustomTabsService.KEY_URL, Common.TECHNO_SPARKS_URI);
            ctSession.mayLaunchUrl(Common.WEBSITE_URI, null, Arrays.asList(maxr1998Website, technoSparksProfile));
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    String cctPackageName = CustomTabsClient.getPackageName(this, Arrays.asList(
            "com.android.chrome", "com.chrome.beta", "com.chrome.dev", "org.mozilla.firefox", "org.mozilla.firefox_beta"
    ));
    if (cctPackageName != null) {
        CustomTabsClient.bindCustomTabsService(this, cctPackageName, ctConnection);
    } else ctConnection = null;
}