- Android Intents with Chrome
- # Syntax
- # Examples
- # Considerations
- # See also
- Открытие URL-ссылок с помощью Android-приложения (Deep Links)
- Что такое Deep Links и как интегрировать их в своё приложение
- Как работает открытие ссылок через приложение и зачем оно вообще нужно?
- Разделение на Deep Links и Android App Links
- 1. Deep Links
- 2. Android App Links
- Постановка задачи
- Реализация
- Урок 31. Вызываем браузер, звонилку, карты с помощью intent с атрибутом data — Uri | Уроки Android Studio
- Android App Linking
- Web url
- Android
- Features
- Pros and Cons
- App Links
- Android
- Features
- Pros and Cons
- Custom scheme
- Android
- Features
- Pros and Cons
- Intent scheme
- Android
- Features
- Pros and Cons
- App scheme
- Android
- Features
- Pros and Cons
- Firebase Dynamic Links
- Android
- Features
- Pros and Cons
- Play Store url
- Android
- Features
- Pros and Cons
- Market scheme
- Android
- Features
- Pros and Cons
- Referrer Receiver
- Deeplinking
- Deferred deeplink
- Url redirections
- Adb Activity Manager
Android Intents with Chrome
Published on Friday, February 28, 2014
A little known feature in Android lets you launch apps directly from a web page via an Android Intent. One scenario is launching an app when the user lands on a page, which you can achieve by embedding an iframe in the page with a custom URI-scheme set as the src , as follows: . This works in the Chrome for Android browser, version 18 and earlier. It also works in the Android browser, of course.
The functionality has changed slightly in Chrome for Android, versions 25 and later. It is no longer possible to launch an Android app by setting an iframe’s src attribute. For example, navigating an iframe to a URI with a custom scheme such as paulsawesomeapp:// will not work even if the user has the appropriate app installed. Instead, you should implement a user gesture to launch the app via a custom scheme, or use the «intent:» syntax described in this article.
# Syntax
The best practice is to construct an intent anchor and embed that into the page so the user can launch the app. This gives you a lot more flexibility in controlling how apps are launched, including the ability to pass extra information into the app via Intent Extras.
The basic syntax for an intent-based URI is as follows:
See the Android source for parsing details.
Also, you may choose to specify fallback URL by adding the following string extra:
When an intent could not be resolved, or an external application could not be launched, then the user will be redirected to the fallback URL if it was given.
Some example cases where Chrome does not launch an external application are as follows:
- The intent could not be resolved, i.e., no app can handle the intent.
- JavaScript timer tried to open an application without user gesture.
Note that S. is a way to define string extras. S.browser_fallback_url was chosen for backward compatibility, but the target app won’t see browser_fallback_url value as Chrome removes it.
# Examples
Here’s an intent that launches the Zxing barcode scanner app. It follows the syntax thus:
To launch the Zxing barcode scanner app, you encode your href on the anchor as follows:
See the Android Zxing Manifest, which defines the package and the host.
Also, if fallback URL is specified, the full URL will look like this:
Now the URL will get you to zxing.org if the app could not be found, or the link was triggered from JavaScript without user gesture (or for other cases where we don’t launch an external application.)
# Considerations
If the activity you invoke via an intent contains extras, you can include these as well.
Only activities that have the category filter, android.intent.category.BROWSABLE are able to be invoked using this method as it indicates that the application is safe to open from the Browser.
# See also
And Chrome doesn’t launch an external app for a given Intent URI in the following cases.
- When the Intent URI is redirected from a typed in URL.
- When the Intent URI is initiated without user gesture.
Last updated: Friday, February 28, 2014 • Improve article
Источник
Открытие URL-ссылок с помощью Android-приложения (Deep Links)
Что такое Deep Links и как интегрировать их в своё приложение
Apr 28, 2018 · 3 min read
Как работает открытие ссылок через приложение и зачем оно вообще нужно?
Нередко бывает так, что определённому контенту соответствует и страница на сайте, и экран в приложен и и. В таких случаях пользователю, у которого установлено приложение, удобно будет открывать ссылку на этот контент через приложение. Как пример можно взять интернет-магазин. Пользователь может нажать на ссылку в браузере, после чего ему предложит просмотреть страницу товара через приложение. Также это хорошо используется с шарингом ссылок. Пример: Петя увидел классные кроссовки на сайте и скинул ссылку на них Васе в Telegram. У Васи уже установлено приложение интернет-магазина, поэтому он нажав на ссылку в Telegram попадает на экран приложения, в котором отображается вся информация об этих замечательных кроссовках. Удобно, не правда ли?
Разделение на Deep Links и Android App Links
Перед тем, как мы займемся реализацией, важно понять, что есть два способа обработки ссылок:
1. Deep Links
Глубокие ссылки (Deep Links) — это URL, которые направляют пользователя на определённый контент в вашем приложении. Они реализуются созданием интент-фильтра и извлечением информации из входящих интентов. Если на телефоне установлены приложения, которые могут обрабатывать такие же интенты, то пользователю будет предложено несколько приложений на выбор, и он сможет выбрать через какое открыть ссылку.
2. Android App Links
Android App Links доступны только с Android 6.0 (API 23) и позволяют назначать приложение дефолтным обработчиком ссылок определённого типа. Главное отличие от Deep Links заключается в том, что никакое другое приложение кроме вашего не сможет обработать ссылку.
В этой статье будет рассматриваться первый тип ссылок — Deep Links.
Постановка задачи
Давайте на простом и типичном примере посмотрим как можно добавить обработку глубоких ссылок в приложение.
Допустим, у нас есть сайт с вакансиями, на котором каждой вакансии соответствует ссылка вида https://awesomejobs.com/jobs/
Реализация
- Начнем с добавления нового intent-filter в Activity , на которую мы хотим направлять пользователя. Это нужно для того, чтобы система понимала какого вида ссылки мы хотим обрабатывать. В AndroidManifest.xml нужно добавить следующие строки:
- action android.intent.action.VIEW говорит о том, что Activity предназначена для отображения контента.
- category android.intent.category.BROWSABLE требуется для того, чтобы мобильный браузер смог выполнить открытие ссылки из результатов поиска Google. Без этого аттрибута при клике по ссылке в мобильном браузере она будет открываться в самом же браузере.
category android.intent.category.DEFAULT требуется если вы хотите чтобы приложение обрабатывало ссылку с любого ссылающегося сайта. Интент, который используется при переходе из результатов поиска Google знает, что должен открыть именно ваше приложение, поэтому явно указывает на него как на получателя. Ссылки же с других сайтов не знают ничего о вашем приложении, поэтому категория DEFAULT говорит о том, что приложение способно принять неявный Intent от них.
2. Наше приложение научилось ловить интенты извне, теперь нам нужно написать код для того, чтобы перехватывать их, доставать id вакансии и с ним уже делать всё, что нам захочется (запрашивать с сервера информацию о вакансии с таким id и отображать её, например).
Для этого в метод onCreate активити, которую мы использовали в манифесте, добавим следующий код:
Активити запускается интентом, содержащем в себе ссылку. data — это и есть не что иное, как наша ссылка. Получив её и выполнив необходимые проверки, мы вырезаем из неё id вакансии, подтягиваем её детали с сервера и отображаем на экране. Всё предельно просто.
Источник
Урок 31. Вызываем браузер, звонилку, карты с помощью intent с атрибутом data — Uri | Уроки Android Studio
В этом уроке мы создадим приложение, которое будет вызывать системные приложения: интернет-браузер — чтобы открыть ссылку, диалер — чтобы позвонить по номеру, и приложение Google-карты — чтобы показать на карте заранее определенные координаты.
Скачать файлы для установки Google Apps на эмулятор Genymotion
Код проекта — под видео:
Больше уроков:
Инструменты android разработчика: тут
Дизайн android приложений: тут
Уроки создания игр для android: тут
Основы программирования на JAVA: тут
Здравствуйте Виталий! Большое спасибо за Ваши уроки, которые очень грамотно преподносятся, что даже такой далекий от программирования человек, как я, смог разобраться. У меня к Вам вопрос: при вызове intent c действием ACTION_CALL происходит звонок по заданному в Uri номеру, можно ли программно узнать когда абонент поднимет трубку? Заранее благодарен за помощь.
Для отправки комментария вам необходимо авторизоваться.
Источник
Android App Linking
The ultimate developer guide to Android application linking methods
The main objectives of this guide are to explore the most common deeplinking methods available on Android and evaluate their pros and cons.
The source code of the AppLinks Android app is available on the corresponding GitHub repository.
Method | Link | App not installed | Offline | Referrer | Deeplink | Deferred deeplink |
---|---|---|---|---|---|---|
Web url | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
App Links | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
Custom scheme | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
Intent scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ❌ |
App scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ❌ |
Firebase Dynamic Links | Test | ✔️ | ❌ | ❌ | ✔️ | ✔️ |
Play Store url | Test | ✔️ | ✔️ | ✔️ | ❌ | ✔️ |
Market scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Web url
http://smarquis.fr/action?key=value#data
Android
Uri | Value |
---|---|
scheme | http |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Initial disambiguation dialog
- Doesn’t work on the same domain
- Some (in-app) browsers might directly handle these links and prevent the app to launch
App Links
https://smarquis.fr/action?key=value#data
A JSON verification file needs to be available at https://smarquis.fr/.well-known/assetlinks.json containing the application’s package name and keystore fingerprint
To test an existing statement file, you can use the official Statement List Generator and Tester tool.
During app install/update, an Android service will verify if the App Links configuration complies with the server side assetlinks.json file.
The results will be sent to logcat, with these tags: IntentFilterIntentSvc and SingleHostAsyncVerifier
Click to see logcat content
Valid App Links configuration
Invalid App Links configuration (missing or malformed assetlinks.json file, missing package_name or sha256_cert_fingerprints )
Android
Same as Web url but with https only and android:autoVerify=»true» attribute.
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- No more disambiguation dialog
- No potential app hijacking
- Doesn’t work on the same domain
- Some (in-app) browsers might directly handle these links and prevent the app to launch
Custom scheme
link://smarquis.fr/action?key=value#data
Android
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
Intent scheme
intent://smarquis.fr/action?key=value#data#Intent;scheme=link;package=fr.smarquis.applinks;S.key=value;S.market_referrer=my%20referrer%20data;end
Extra parameters can be added to the link and will be transfered as extras Bundle in the Intent :
- String: S.key=value
- Boolean: B.key=value
- Integer: i.key=value
- Long: l.key=value
- Float: f.key=value
- S.browser_fallback_url is the fallback URL if the corresponding link doesn’t work of if app isn’t available (will be removed from the Intent ).
- S.market_referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the parseUri() method from the Android source code.
The new url will be link://smarquis.fr/action?key=value#data
And will contain additional parameters in the Intent .
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Extra | Value |
---|---|
key | value |
market_referrer | my referrer data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
App scheme
android-app://fr.smarquis.applinks/https/smarquis.fr/action?key=value#data#Intent;S.key=value;S.market_referrer=my%20referrer%20data;end
Extra parameters can be added to the link and will be transfered as extras Bundle in the Intent :
- String: S.key=value
- Boolean: B.key=value
- Integer: i.key=value
- Long: l.key=value
- Float: f.key=value
- S.market_referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the parseUri() method from the Android source code.
The new url will be https://smarquis.fr/action?key=value#data
And will contain additional parameters in the Intent .
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Extra | Value |
---|---|
key | value |
market_referrer | my referrer data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
Firebase Dynamic Links
https://mr7f2.app.goo.gl/Tbeh
Create the link from the Firebase console.
Android
Same requirements as App Links.
And add the Firebase Dynamic Links dependency in the app-level build.gradle file:
Then in your Activity ‘s onCreate method, use this code to get the link if the user came from a Firebase Dynamic Link:
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ❌ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ✔️ |
Pros and Cons
- Ugly progress dialog when fetching link data
Play Store url
https://play.google.com/store/apps/details?id=fr.smarquis.applinks&url=link%3A%2F%2Fsmarquis.fr%2Faction%3Fkey%3Dvalue%23data&referrer=my%20referrer%20data
Very similar to the Market scheme.
This url contains additional query parameters that will be handled by the Play Store app:
- url is the forwarded url
- referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the Play Store to link://smarquis.fr/action?key=value#data
Uri available in deferred deeplink only
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ❌ |
Deferred deeplink | ✔️ |
Pros and Cons
- Some (in-app) browsers might directly handle these links and prevent the Play Store app to launch
- When app is installed, it still opens the Play Store app and completely ignores the deeplink
- Changes the «Open» button in Play Store to «Continue»
- Triggers a notification with «Tap to continue»
Market scheme
market://details?id=fr.smarquis.applinks&url=link%3A%2F%2Fsmarquis.fr%2Faction%3Fkey%3Dvalue%23data&referrer=my%20referrer%20data
This url contains additional query parameters that will be handled by the Play Store app:
- url is the forwarded url
- referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the Play Store to link://smarquis.fr/action?key=value#data
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ✔️ |
Pros and Cons
- Changes the «Open» button in Play Store to «Continue»
- Triggers a notification with «Tap to continue»
Referrer Receiver
Add the Broadcast Receiver in AndroidManifest.xml
And in the Receiver’s onReceive() method, you can get the referrer value
Deeplinking
You can get the deeplink Uri in your Activity ‘s onCreate() method as well as the corresponding properties:
Deferred deeplink
When using Play Store url or Market scheme or Firebase Dynamic Links methods, the regular Play Store Open button will be replaced by a Continue button.
Furthermore, a notification will be displayed with Tap to continue content.
These two actions are essential to the Deferred deeplink method as they provide the initial data to the app.
Regular Deeplink | Deferred Deeplink |
---|
Url redirections
Adb Activity Manager
To try links with adb, use the Activity Manager (am) command:
Источник