- Chrome Custom Tabs in Android
- Introduction
- Why use Chrome Custom tabs?
- How to use Chrome Custom tabs
- 1. Add Chrome Custom tabs to your app
- 2. Open a Chrome custom tab
- 3. Further customization
- a. Setting an Action Button
- b. Adding custom menu items.
- c. Adding entry and exit animations.
- Advanced customization of Chrome custom tabs
- Want to see more code?
- References and Further reading
- Обзор Android 6.0
- Поддержка USB Type-C
- Поиск Google Now в приложениях
- Chrome Custom Tabs
- Новая панель буфера обмена
- Упрощенная регулировка громкости
- Обновленный список приложений
- Overview
- # When should I use Custom Tabs vs WebView?
- # When should I use Custom Tabs vs Trusted Web Activity
- # Where is Custom Tabs available?
- # Getting Started
Chrome Custom Tabs in Android
Introduction
I have been seeing a behaviour in some apps for a while, and I’ve always wanted to know how it was done. I noticed some apps that allow to view urls within the app, used something that is “Powered by Chrome”. I first noticed this on the Twitter for Android app, then on Medium, then Feedly.
I was interested in knowing how these worked, but I didn’t know what to search for. Finally, a few weeks ago, I stumbled on “Chrome Custom Tabs”. Alas, that was what I was looking for.
In this post, I’m going to explain why, when and how to use “Chrome Custom Tabs” in your Android applications.
Why use Chrome Custom tabs?
When building apps, developers are usually faced with difficult tradeoffs to make when we have to show web content in our Android apps. Very common and easy solution is to open links externally. If you do this, then these lines of code will look familiar:
This typically results in a heavy-weight transition between the app and web. Launching a browser from your app to view web content results in a huge context switch which isn’t customizable, and hence could lead to a terrible experience.
An improvement on this experience will be to use a WebView which is essentially an Android view that displays web pages. However, this options requires technical work to implement and delivers a browsing experience that the users aren’t used to.
To solve this problem, the Google Chrome team introduced a new feature last September, called custom tabs. This allows to load a chrome tab within your app, and also allows you customize the look and feel of Chrome thereby making the transition between your app and the web content fast & seamless for your users.
This is Chrome Custom tab in action on Twitter for Android app:
Chrome Custom tab allows you customize the experience of Chrome. It allows you customize:
- Toolbar color
- Enter and exit animations
- Add custom actions to the Chrome toolbar, overflow menu and bottom toolbar
How to use Chrome Custom tabs
1. Add Chrome Custom tabs to your app
First thing to do, is to add the chrome custom tabs dependency to the dependencies section of your app-level build.gradle file. The section should look like this
With this, you can customize the look and feel of Chrome, and also take advantage of some optimizations, as we will see later in the post.
2. Open a Chrome custom tab
Next step is to proceed to open a Chrome custom tab. In this step, you get to configure the look and feel of Chrome open a url in the Chrome Custom Tab. This happens in 3 easy steps:
- Create a CustomTabsIntent builder for customization. Specify all the custom properties you desire.
- Build a CustomTabsIntent from the builder
- Launch the url.
This block of code, does exactly the 3 things listed above:
3. Further customization
a. Setting an Action Button
You can set an action button and customize that action button.
An action button is what is highlighted by the red box in the image below:
b. Adding custom menu items.
You can also add custom menu items. To do this, follow these steps:
Custom menu items added are as highlighted in the image below:
c. Adding entry and exit animations.
It’s also possible to specify custom entry and exit animations. To do this, follow these steps:
Advanced customization of Chrome custom tabs
There are other advanced customizations you can do, especially when it comes to optimization. Chrome Custom Tabs allows for:
- Warming up Chrome to make pages load faster,
- Tell Chrome what the user is likely to open, and then allow for prefetching the content,
- Create a new tab session,
- Connection to the Chrome service,
- Custom Tabs connection callbacks,
- Create fallbacks when there is no version of Chrome that supports Chrome Custom Tabs, or where there isn’t chrome at all.
Want to see more code?
Clone or download this github repo for the full source code to demo Chrome Custom Tabs.
The repository contains code to customize the tabs, helper methods, more code on the optimization, warming, binding to a Chrome Tab Connection, Unbinding at the right time, fallback method, for when the device doesn’t have Chrome installed.
References and Further reading
This post is just an introduction to using Chrome Custom Tabs, feel free to explore more resources to gain a deeper insight into using Chrome custom tabs.
Here are some references and resources for further reading:
If you have any comments/suggestions or corrections, I’d love to hear them. Please do not hesitate to drop a comment below or tweet at me.
Please share if this post has helped you in some way, or you know someone it may be of help to. 🙈😁
Источник
Обзор Android 6.0
Поддержка USB Type-C
Стандарт USB Type-C или просто USB-C постепенно набирает популярность. Вкратце напомним, что он появился вместе со спецификацией USB 3.1, одной из главных особенностей которых стало удвоение пропускной способности интерфейса до 10 Гбит/с относительно USB 3.0. Ну а USB Type-C – это тип соединения, предполагающий новый разъем, который может быть одинаковым на всех устройствах.
Разумеется, возможность подключить кабель любой стороной не есть главная фича USB Type-C. Помимо этого он добавляет много дополнительных функций, в том числе продвинутые возможности зарядки, согласно спецификации USB Power Delivery 2.0. В частности речь идет о силе тока 1,5 и 3,0 А при напряжении 5 В.
Android 6.0, как вы догадались, поддерживает USB Type-C, а вместе с ним еще и продвинутые режимы зарядки. Нет, мы не только о повышенной силе тока, дающей прирост скорости зарядки, но еще и о таких вещах, как подзарядка других устройств. Речь идет о том, что можно будет заряжать телефоны, смартфоны и планшеты друг от друга: телефон от планшета, смартфон от планшета и даже планшет от смартфона, а также иные «извращенные» варианты. Вряд ли эта функция станет везде и всеми востребована, но в определенных ситуациях будет полезна.
Кроме того, к устройствам на Android 6.0 и с разъемом USB Type-C можно будет подключить MIDI-клавиатуры. Это еще больше расширит мультимедийную составляющую Android.
Поиск Google Now в приложениях
На самом деле эта функция называется «Google Now on Tap» и вызывается она, если долго удерживать нажатой кнопку Домой. После запуска Google Now «просканирует» то, что находится на экране, и предложит карточку с дополнительной информацией.
Идея там в следующем. Допустим, вы обсуждаете с кем-то какой-либо фильм или новый музыкальный альбом, какое-то место и так далее. Контекст из вашего экрана сообщений очевиден и его Google Now сможет понять. Долгое удержание кнопки Домой приведет к тому, что этот самый контекст будет распознан и согласно ему будет предложена карточка с информацией: справка о фильме из базы IMDb, сведения о стране, информация о альбоме и так далее.
Причем возможности Google Now on Tap заметно шире – информация может черпаться не только из поиска Google, но также и из установленных приложений. Здесь главное, чтобы соответствующую функциональность реализовали их разработчики – предоставили возможность индексирования данных внутри программ.
Другими словами Google Now on Tap – это своего рода интеллектуальный помощник, работающий в любом приложении и дающий полезные подсказки, если они необходимы. Теоретически его функционированию ничего не должно помешать, разве что разработчик сделает совершенно нетипичный интерфейс приложения.
Chrome Custom Tabs
Любой разработчик может встроить браузер в свое приложение на Android. Для этого создан соответствующий компонент, обеспечивающий работу движка рендеринга веб-страницы внутри вашего приложения. Но здесь есть один неприятный момент – все это никак не связано с основным системным браузером. То есть ваши введенные пароли, история поиска, сохраненные Cookie и так далее там недоступны.
Теперь эта проблема может быть решена, если встроить в свое приложение «кусок» браузера Chrome. По факту функциональность останется той же, но повторно вводить пароли не придется, а сайты вас будут помнить.
Вместе с тем добавилась еще одна интересная функция – открытие ссылок в приложениях. Допустим, вы нажимаете на ссылку на страницу Facebook, Twitter, ВКонтакте и тому подобное, а далее вам предложат открыть ее в соответствующем клиенте, если он у вас установлен.
Новая панель буфера обмена
Пользоваться буфером обмена, тем самым «копипастом», в Android не всегда просто. Если кто помнит, то, выделив фрагмент текста, сверху появляется панель с опциями копировать, вставить, вырезать, выделить все и тому подобное. Все бы хорошо, но сообразить, что надо смотреть вверх экрана, особенно на большом дисплее, не всегда получается сразу.
В Android 6.0 теперь соответствующая панель будет отображаться рядом с выделенным текстом. Это уже реализовано в iOS и, сюрприз-сюрприз, Windows Phone. Google теперь догнала конкурентов, хотя пока работает новая панель не очень хорошо.
Упрощенная регулировка громкости
Android 5.0 так намудрил с регулировкой громкости, что ого-го! Если до него, доводя громкость до минимума, сначала выключался звук, а еще одним нажатием кнопки – вибрация, то в «пятерочке» полностью «тихого» режима не осталось. Вместо этого предлагалось выбрать один из трех вариантов: оставить вибрацию для всех уведомлений, для приоритетных или все-таки замолчать до иных приказаний.
Android 6.0 возвращает прежнюю функциональность – «заглушить» смартфон или планшет можно нажатием кнопки громкость вниз. Но, при необходимости, можно настроить какие события и уведомления будут слышны.
Обновленный список приложений
Список приложений в Android 5 стал таким светлым, с белым фоном. Многим это, кстати, не очень понравилось. Думаете, Android 6.0 «потемнел»? Отнюдь, но новые возможности здесь появились.
Прежде всего вернулся старый способ перемотки приложений – вертикальным листанием, вместо горизонтального. Причем слева теперь выведены буквы алфавита для более наглядной группировки. Мы не исключаем, что это вовсе не финальный вариант дизайна.
Еще в самом верху появилось поле поиска по приложениям, а прямо под ним – четверка наиболее часто используемых программ. На первый взгляд выглядит удобно.
Источник
Overview
Published on Tuesday, February 4, 2020 • Updated on Tuesday, February 2, 2021
App developers face a choice when a user taps a URL to either launch a browser, or build their own in-app browser using WebViews.
Both options present challenges — launching the browser is a heavy context switch for users that isn’t customizable, while WebViews don’t support all features of the web platform, don’t share state with the browser and add maintenance overhead.
Custom Tabs is a browser feature, introduced by Chrome, that is now supported by most major browsers on Android. It give apps more control over their web experience, and make transitions between native and web content more seamless without having to resort to a WebView.
Note: For information on sharing the content in Custom Tabs, see the blog post, Better content sharing with Custom Tabs.
Custom Tabs allow an app to customize how the browser looks and feels. An app can change things like:
- Toolbar color
- Enter and exit animations
- Add custom actions to the browser toolbar, overflow menu and bottom toolbar
Custom Tabs also allow the developer to pre-start the browser and pre-fetch content for faster loading.
You can test this now with our sample on GitHub.
# When should I use Custom Tabs vs WebView?
The WebView is good solution if you are hosting your own content inside your app. If your app directs people to URLs outside your domain, we recommend that you use Custom Tabs for these reasons:
- Support for the same web platform features and capabilities as the browsers.
- Simple to implement. No need to build code to manage requests, permission grants or cookie stores.
- UI customization:
- Toolbar color
- Action button
- Custom menu items
- Custom in/out animations
- Bottom toolbar
- Toolbar color
- Navigation awareness: the browser delivers a callback to the application upon an external navigation.
- Security: the browser uses Google’s Safe Browsing to protect the user and the device from dangerous sites.
- Performance optimization:
- Pre-warming of the Browser in the background, while avoiding stealing resources from the application.
- Providing a likely URL in advance to the browser, which may perform speculative work, speeding up page load time.
- Lifecycle management: the browser prevents the application from being evicted by the system while on top of it, by raising its importance to the «foreground» level.
- Shared cookie jar and permissions model so users don’t have to sign-in to sites they are already connected to, or re-grant permissions they have already granted.
- If the user has turned on Data Saver, they will still benefit from it.
- Synchronized AutoComplete across devices for better form completion.
- Simple customization model.
- Quickly return to app with a single tap.
- You want to use the latest browser implementations on devices pre-Lollipop (auto updating WebView) instead of older WebViews.
# When should I use Custom Tabs vs Trusted Web Activity
Trusted Web Activities extend the Custom Tabs protocol and shares most of its benefits. But, instead of providing a customized UI, it allows developers to open a browser tab without any UI at all. It is recommended for developers who want to open their own Progressive Web App, in full screen, inside their own Android app.
# Where is Custom Tabs available?
Custom Tabs is a feature supported by browsers on the Android platform. It was originally introduced by Chrome, on version 45. Currently, the protocol is supported by most Android browsers.
We are looking for feedback, questions and suggestions on this project, so we encourage you to file issues on crbug.com and ask questions to our Twitter account @ChromiumDev.
# Getting Started
If you are getting started with Custom Tabs, checkout the Implementation Guide and the GitHub Demo.
For questions, check the chrome-custom-tabs tag on StackOverflow.
Last updated: Tuesday, February 2, 2021 Improve article
Источник