androidx.browser.customtabs.CustomTabsSession Java Examples

The following examples show how to use androidx.browser.customtabs.CustomTabsSession. 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: WebContent.java    From deagle with Apache License 2.0 6 votes vote down vote up
/** Caller must unbind the returned ServiceConnection when leaving the scope. */
public static @CheckResult @Nullable ServiceConnection preload(final Context context, final Uri uri, final @Nullable OnSessionReadyListener listener) {
	final CustomTabsServiceConnection connection;
	if (! CustomTabsClient.bindCustomTabsService(context, KChromePackageName, connection = new CustomTabsServiceConnection() {

		@Override public void onCustomTabsServiceConnected(final ComponentName componentName, final CustomTabsClient client) {
			Log.d(TAG, "Warming up Chrome custom tabs");
			if (client.warmup(0)) {
				final CustomTabsSession session = client.newSession(null);
				if (session != null) {
					session.mayLaunchUrl(uri, null, null);
					if (listener != null) listener.onSessionReady(session);
				}
			}
		}

		@Override public void onServiceDisconnected(final ComponentName name) {}
	})) return null;
	return connection;
}
 
Example #2
Source File: PwaWrapperSplashScreenStrategy.java    From android-browser-helper with Apache License 2.0 6 votes vote down vote up
@Override
public void configureTwaBuilder(TrustedWebActivityIntentBuilder builder,
        CustomTabsSession session,
        Runnable onReadyCallback) {
    if (!mProviderSupportsSplashScreens || mSplashImage == null) {
        onReadyCallback.run();
        return;
    }
    if (TextUtils.isEmpty(mFileProviderAuthority)) {
        Log.w(TAG, "FileProvider authority not specified, can't transfer splash image.");
        onReadyCallback.run();
        return;
    }
    mSplashImageTransferTask = new SplashImageTransferTask(mActivity,
            mSplashImage, mFileProviderAuthority, session,
            mProviderPackage);

    mSplashImageTransferTask.execute(
            success -> onSplashImageTransferred(builder, success, onReadyCallback));
}
 
Example #3
Source File: CustomTabConnectionRule.java    From android-browser-helper with Apache License 2.0 6 votes vote down vote up
/**
 * Binds the CustomTabsService, creates a {@link CustomTabsSession} and returns it.
 */
public CustomTabsSession establishSessionBlocking(Context context) {
    mContext = context;
    if (!CustomTabsClient.bindCustomTabsService(context, context.getPackageName(),
            mConnection)) {
        fail("Failed to bind the service");
        return null;
    }
    boolean success = false;
    try {
        success = mConnectionLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {}
    if (!success) {
        fail("Failed to connect to service");
        return null;
    }
    return mSession;
}
 
Example #4
Source File: CustomTabManager.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link androidx.browser.customtabs.CustomTabsSession custom tab session} for
 * use with a custom tab intent, with optional callbacks and optional list of URIs that may
 * be requested. The URI list should be ordered such that the most likely URI to be requested
 * is first. If no custom tab supporting browser is available, this will return {@code null}.
 */
@WorkerThread
@Nullable
public CustomTabsSession createSession(
        @Nullable CustomTabsCallback callbacks,
        @Nullable Uri... possibleUris) {
    CustomTabsClient client = getClient();
    if (client == null) {
        return null;
    }

    CustomTabsSession session = client.newSession(callbacks);
    if (session == null) {
        Logger.warn("Failed to create custom tabs session through custom tabs client");
        return null;
    }

    if (possibleUris != null && possibleUris.length > 0) {
        List<Bundle> additionalUris = UriUtil.toCustomTabUriBundle(possibleUris, 1);
        session.mayLaunchUrl(possibleUris[0], null, additionalUris);
    }

    return session;
}
 
Example #5
Source File: AppUtils.java    From materialistic with Apache License 2.0 6 votes vote down vote up
@NonNull
private static Intent createViewIntent(Context context, @Nullable WebItem item,
                                       String url, @Nullable CustomTabsSession session) {
    if (Preferences.customTabsEnabled(context)) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(session)
                .setToolbarColor(ContextCompat.getColor(context,
                        AppUtils.getThemedResId(context, R.attr.colorPrimary)))
                .setShowTitle(true)
                .enableUrlBarHiding()
                .addDefaultShareMenuItem();
        if (item != null) {
            builder.addMenuItem(context.getString(R.string.comments),
                    PendingIntent.getActivity(context, 0,
                            new Intent(context, ItemActivity.class)
                                    .putExtra(ItemActivity.EXTRA_ITEM, item)
                                    .putExtra(ItemActivity.EXTRA_OPEN_COMMENTS, true),
                            PendingIntent.FLAG_ONE_SHOT));
        }
        return builder.build().intent.setData(Uri.parse(url));
    } else {
        return new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    }
}
 
Example #6
Source File: AppUtils.java    From materialistic with Apache License 2.0 6 votes vote down vote up
public static void openExternal(@NonNull final Context context,
                         @NonNull PopupMenu popupMenu,
                         @NonNull View anchor,
                         @NonNull final WebItem item,
                         final CustomTabsSession session) {
    if (TextUtils.isEmpty(item.getUrl()) ||
            item.getUrl().startsWith(HackerNewsClient.BASE_WEB_URL)) {
        openWebUrlExternal(context,
                item, String.format(HackerNewsClient.WEB_ITEM_PATH, item.getId()),
                session);
        return;
    }
    popupMenu.create(context, anchor, GravityCompat.END)
            .inflate(R.menu.menu_share)
            .setOnMenuItemClickListener(menuItem -> {
                openWebUrlExternal(context, item, menuItem.getItemId() == R.id.menu_article ?
                        item.getUrl() :
                        String.format(HackerNewsClient.WEB_ITEM_PATH, item.getId()), session);
                return true;
            })
            .show();
}
 
Example #7
Source File: ManageDataLauncherActivity.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
private static boolean launchBrowserSiteSettings(Activity activity, CustomTabsSession session,
        String packageName, Uri defaultUri) {
    // CustomTabsIntent builder is used just to put in the session extras.
    Intent intent = new CustomTabsIntent.Builder().setSession(session).build().intent;
    intent.setAction(ACTION_MANAGE_TRUSTED_WEB_ACTIVITY_DATA);
    intent.setPackage(packageName);
    intent.setData(defaultUri);
    try {
        activity.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        return false;
    }
}
 
Example #8
Source File: CustomTabActivityHelper.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
public boolean mayLaunchUrl(Uri uri, Bundle extras, List<Bundle> otherLikelyBundles) {
    if (mClient == null) return false;

    CustomTabsSession session = getSession();
    if (session == null) return false;

    return session.mayLaunchUrl(uri, extras, otherLikelyBundles);
}
 
Example #9
Source File: CustomTabActivityHelper.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
/**
 * Creates or retrieves an exiting CustomTabsSession
 *
 * @return a CustomTabsSession
 */
public CustomTabsSession getSession() {
    if (mClient == null) {
        mCustomTabsSession = null;
    } else if (mCustomTabsSession == null) {
        mCustomTabsSession = mClient.newSession(null);
    }
    return mCustomTabsSession;
}
 
Example #10
Source File: CustomTabsDelegate.java    From materialistic with Apache License 2.0 5 votes vote down vote up
/**
 * Creates or retrieves an exiting CustomTabsSession.
 *
 * @return a CustomTabsSession.
 */
CustomTabsSession getSession() {
    if (mClient == null) {
        mCustomTabsSession = null;
    } else if (mCustomTabsSession == null) {
        mCustomTabsSession = mClient.newSession(null);
    }
    return mCustomTabsSession;
}
 
Example #11
Source File: CustomTabsDelegate.java    From materialistic with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if call to mayLaunchUrl was accepted.
 * @see CustomTabsSession#mayLaunchUrl(Uri, Bundle, List)
 */
public boolean mayLaunchUrl(Uri uri, Bundle extras, List<Bundle> otherLikelyBundles) {
    if (mClient == null) {
        return false;
    }
    CustomTabsSession session = getSession();
    return session != null && session.mayLaunchUrl(uri, extras, otherLikelyBundles);
}
 
Example #12
Source File: AppUtils.java    From materialistic with Apache License 2.0 5 votes vote down vote up
public static void openWebUrlExternal(Context context, @Nullable WebItem item,
                                      String url, @Nullable CustomTabsSession session) {
    if (!hasConnection(context)) {
        context.startActivity(new Intent(context, OfflineWebActivity.class)
                .putExtra(OfflineWebActivity.EXTRA_URL, url));
        return;
    }
    Intent intent = createViewIntent(context, item, url, session);
    if (!HackerNewsClient.BASE_WEB_URL.contains(Uri.parse(url).getHost())) {
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
        return;
    }
    List<ResolveInfo> activities = context.getPackageManager()
            .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    ArrayList<Intent> intents = new ArrayList<>();
    for (ResolveInfo info : activities) {
        if (info.activityInfo.packageName.equalsIgnoreCase(context.getPackageName())) {
            continue;
        }
        intents.add(createViewIntent(context, item, url, session)
                .setPackage(info.activityInfo.packageName));
    }
    if (intents.isEmpty()) {
        return;
    }
    if (intents.size() == 1) {
        context.startActivity(intents.remove(0));
    } else {
        context.startActivity(Intent.createChooser(intents.remove(0),
                context.getString(R.string.chooser_title))
                .putExtra(Intent.EXTRA_INITIAL_INTENTS,
                        intents.toArray(new Parcelable[intents.size()])));
    }
}
 
Example #13
Source File: CustomTabActivityHelper.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
/**
 * @see {@link CustomTabsSession#mayLaunchUrl(Uri, Bundle, List)}.
 * @return true if call to mayLaunchUrl was accepted.
 */
public boolean mayLaunchUrl(Uri uri, Bundle extras, List<Bundle> otherLikelyBundles) {
    if (mClient == null) return false;

    CustomTabsSession session = getSession();
    if (session == null) return false;

    return session.mayLaunchUrl(uri, extras, otherLikelyBundles);
}
 
Example #14
Source File: CustomTabActivityHelper.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
/**
 * Creates or retrieves an exiting CustomTabsSession.
 *
 * @return a CustomTabsSession.
 */
public CustomTabsSession getSession() {
    if (mClient == null) {
        mCustomTabsSession = null;
    } else if (mCustomTabsSession == null) {
        mCustomTabsSession = mClient.newSession(null);
    }
    return mCustomTabsSession;
}
 
Example #15
Source File: SplashImageTransferTask.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
/**
 * @param context {@link Context} to use.
 * @param bitmap image to transfer.
 * @param authority {@link FileProvider} authority.
 * @param session {@link CustomTabsSession} to use for transferring the file.
 * @param providerPackage Package name of the Custom Tabs provider.
 */
public SplashImageTransferTask(Context context, Bitmap bitmap, String authority,
        CustomTabsSession session, String providerPackage) {
    mContext = context.getApplicationContext();
    mBitmap = bitmap;
    mAuthority = authority;
    mSession = session;
    mProviderPackage = providerPackage;
}
 
Example #16
Source File: ManageDataLauncherActivity.java    From android-browser-helper with Apache License 2.0 5 votes vote down vote up
private void launchSettings(CustomTabsSession session) {
    boolean success = launchBrowserSiteSettings(ManageDataLauncherActivity.this,
            session, mProviderPackage, getDefaultUrlForManagingSpace());
    if (success) {
        finish();
    } else {
        handleNoSupportForManageSpace();
    }
}
 
Example #17
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 #18
Source File: SettingsActivity.java    From MaxLock with GNU General Public License v3.0 4 votes vote down vote up
public CustomTabsSession getSession() {
    return ctSession;
}
 
Example #19
Source File: WebContent.java    From deagle with Apache License 2.0 4 votes vote down vote up
/** This method may never be called if Chrome Custom Tabs are not supported on device, or session is failed to create. */
void onSessionReady(CustomTabsSession session);
 
Example #20
Source File: SplashScreenStrategy.java    From android-browser-helper with Apache License 2.0 2 votes vote down vote up
/**
 * Called when TWA is ready to be launched.
 * @param builder {@link TrustedWebActivityIntentBuilder} to be supplied with splash screen
 * related parameters.
 * @param session {@link CustomTabsSession} with which the TWA will launch.
 * @param onReadyCallback Callback to be triggered when splash screen preparation is finished.
 * TWA is launched immediately upon triggering this callback.
 */
void configureTwaBuilder(TrustedWebActivityIntentBuilder builder, CustomTabsSession session,
        Runnable onReadyCallback);