16 June 2015

Android integration with Chrome Custom Tabs


Announced at Google IO 2015 was the ability to integrate custom tabs in Android. Much like Facebook has been using it’s own browser like tab to open links, this ability is now available in Android with Chrome. This is great news as it allows developers to integrate a web link and maintain some of the look and feel of their app. You can add toolbar colors, animations and even a button.


Before going any further as of June 2015 you need to install Chrome from the dev channel:
Version 45 has this feature, they say it’ll take about twelve weeks to roll through to release.

This works in any version of Android, so don’t worry about M or any of that. It degrades really nicely, so if your client has the feature in Chrome, it’ll slide in and out beautifully. If not, then it’ll open like a regular intent. Although your custom in animation will probably show.

First you need to create four standard in and out animations, left in, left out, right in, right out.
Then you need to define some final constants which will be used in the intent extras:
private static final String EXTRA_CUSTOM_TABS_SESSION_ID = "android.support.CUSTOM_TABS:session_id";
public static final String EXTRA_CUSTOM_TABS_EXIT_ANIMATION_BUNDLE = "android.support.CUSTOM_TABS:exit_animation_bundle";
private static final String EXTRA_CUSTOM_TABS_TOOLBAR_COLOR = "android.support.CUSTOM_TABS:toolbar_color";

Then you can launch like this from your activity:

String url = "http://www.google.com/";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra(EXTRA_CUSTOM_TABS_SESSION_ID, -1);
intent.putExtra(EXTRA_CUSTOM_TABS_TOOLBAR_COLOR, getResources().getColor(R.color.colorPrimary));

if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    Bundle finishBundle = ActivityOptions.makeCustomAnimation(MainActivity.this, R.anim.slide_in_left, R.anim.slide_out_right).toBundle();
    intent.putExtra(EXTRA_CUSTOM_TABS_EXIT_ANIMATION_BUNDLE, finishBundle);
    Bundle startBundle = ActivityOptions.makeCustomAnimation(MainActivity.this, R.anim.slide_in_right, R.anim.slide_out_left).toBundle();
    startActivity(intent, startBundle);
}else{
    startActivity(intent);
}


Note that basically all we are doing is launch an intent.ACTION_VIEW but we’re tweaking it with extras so Chrome can interpret this request, slightly differently.
That’s it!

No comments: