Android url scheme browser

felquis / url-schemes.md

Assume the user is on iOS Safari, but you want it to open an URL on Chrome, Firefox or Opera. How do you do that?

To open on Chrome

check out Chrome iOS Docs for more information

To open on Firefox

Check out Firefox Docs for more information

To open on Opera

Check out this page for more information, I couldn’t found official Opera Documentation

Assume the users is on a in-app webview or any other browser, but an API is not support in-app browser, so you need to link the user to Safari, how do you achieve that?

I couln’t find a URL Scheme for Safari, so I need to link like safari://url so whenever the user clicks on it, it will be handled by Safari.

I tried x-web-search but it didn’t work

Demo and resources

Codepen Demo, Inter App Communication, Apple URL Schemes, I think registerProtocolHandler is somewhat related.. I think this bug is also somewhat related, cause there’s developers trying to figure out if a URL Scheme is available in the platform, check out this Stackoverflow question

Should we work on a standard way to share information between web apps to installed application and installed application to web apps and web apps to web apps, on desktop, tablets and smartphone?

There’s basic necessities when developing a rich web app.

What are the apps the user can share this piece of information?

Whatsapp has the whatsapp:// URL Scheme, but there’s no way to check if the given URL Scheme is available in the platform

If the user clicks in share, the browser/platform should give a list of applications/web apps the user can share the given information, it could be a URL, String, File Buffer would be great, for example.. The user apply a custom filter to an image on a web app. So the user wants to share it on Instagram.

Is a specfic URL Scheme available?

There’s no standard way to check if a URL Scheme is available

How can I offer my web app the oportunite to the user share the information?

Android has a popup where the user choose where he wants to share the information, a URL or String.. or a image base64 enconded.. So. If my web site provide a way to share images, strings and links.. How can I tell the device/browser my web app can share this kind of information?

I found out the best reading these days is this blog post about a failed Web API called Web Indents, follow all the links

Thank you for reading, I appreciate your help.

Источник

WebView — создай свой браузер

Android позволяет создать собственное окно для просмотра веб-страниц или даже создать свой клон браузера при помощи элемента WebView. Сам элемент использует движок WebKit и имеет множество свойств и методов. Мы ограничимся базовым примером создания приложения, с помощью которого сможем просматривать страницы в интернете. В последних версиях используется движок от Chromium, но большой разницы в этом нет для простых задач.

Создадим новый проект MyBrowser и сразу заменим код в файле разметки res/layout/activity_main.xml:

Теперь откроем файл активности MainActivity.java и объявим компонент WebView, а также инициализируем его — включим поддержку JavaScript и укажем страницу для загрузки.

Так как приложение будет использовать интернет, необходимо установить разрешение на доступ к интернету в файле-манифесте.

Там же в манифесте модифицируем строчку для экрана, удалив заголовок из нашего приложения (выделено жирным):

Запустим приложение. В нашем распоряжении появился простейший вьювер веб-страниц, но с одним недостатком. Если вы щёлкнете на любой ссылке, то у вас автоматически запустится браузер по умолчанию и новая страница отобразится уже там. Точнее так было раньше. На новых устройствах при запуске приложения сразу открывается браузер.

Чтобы решить данную проблему и открывать ссылки в своей программе, нужно переопределить класс WebViewClient и позволить нашему приложению обрабатывать ссылки. Добавим в коде вложенный класс:

Затем в методе onCreate() определим экземпляр MyWebViewClient. Он может находиться в любом месте после инициализации объекта WebView:

Теперь в нашем приложении создан WebViewClient, который позволяет загружать любой указанный URL, выбранный в WebView, в сам контейнер WebView, а не запускать браузер. За данную функциональность отвечает метод shouldOverrideUrlLoading(WebView, String), в котором мы указываем текущий WebView и нужный URL. Возвращаемое значение true говорит о том, что мы не нуждаемся в запуске стороннего браузера, а самостоятельно загрузим контент по ссылке. В версии API 24 добавили перегруженную версию метода, учитывайте это обстоятельство.

Читайте также:  Команды голосом для андроид

Повторно запустите программу и убедитесь, что ссылки загружаются теперь в самом приложении. Но теперь возникла ещё одна проблема. Мы не можем вернуться к предыдущей странице. Если мы нажмём на кнопку «BACK» (Назад) на устройстве, то просто закроем своё приложение. Для решения новой проблемы нам необходимо обрабатывать нажатие кнопки «BACK». Добавляем новый метод:

Мы должны проверить, что WebView поддерживает навигацию на предыдущую страницу. Если условие верно, тогда вызывается метод goBack(), который возвращает нас на предыдущую страницу на один шаг назад. Если таких страниц набралось несколько, то мы можем последовательно вернуться к самой первой странице. При этом метод всегда будет возвращать значение true. Когда мы вернёмся на самую первую страницу, с которой начали путешествие по интернету, то вернётся значение false и обработкой нажатия кнопки BACK займётся уже сама система, которая закроет экран приложения.

Запустите приложение ещё раз. У вас появился свой собственный веб-браузер, позволяющий ходить по ссылкам и возвращаться на предыдущую страницу. Изучив документацию, вы можете оснастить приложение и другим вкусными плюшками для своего браузера.

Если вам нужно часть ссылок, ведущих на ваш сайт открывать в браузере, а локальные ссылки открывать в приложении, то применяйте условие с разными возвращаемыми значениями.

Универсальный метод, который все локальные ссылки откроет в приложении, остальные в браузере (меняем одну строчку):

А сейчас немного усложним пример, чтобы у пользователя появилась альтернатива стандартным браузерам.

Чтобы было понятнее, переделаем пример следующим образом. Создайте две активности. На первой активности разместите кнопку для перехода на вторую активность, а на второй активности разместите компонент WebView.

В манифесте прописываем у второй активности фильтр.

Код для кнопки для перехода на вторую активность.

Мы создали собственное намерение с указанием фильтра и предоставили данные — адрес сайта.

Вторая активность должна принять данные:

В фильтре для второй активности мы указали два действия.

Это означает, что любые активности (читай, приложения) могут вызвать вашу активность с мини-браузером по такому же принципу. Запустите в студии в отдельном окне любой старый проект или создайте новый и добавьте в него кнопку и пропишите тот же код, который мы использовали для щелчка кнопки.

Запустите второе приложение (первое приложение можно закрыть) и нажмите на кнопку. У вас запустится не первое приложение с начальным экраном, а сразу вторая активность с мини-браузером. Таким образом, любое приложение может запустить браузер, не зная имени класса вашей активности, а используя только строку «ru.alexanderklimov.Browser», передаваемую в Intent. При этом ваша активность с браузером должна иметь категорию по умолчанию и данные. Напомню:

Вы можете представить свою строку в виде строковой константы и сообщить всем потенциальным пользователям вашего браузера, как они могут запустить его у себя. Но в Android уже есть такая готовая константа ACTION_VIEW, которая по справке документации представляет собой следующее:

Перепишем код для кнопки у второго приложения

Что произойдёт на этот раз? Мы помним, что у нас прописано два действия, включая и android.intent.action.VIEW. А значит наше первое приложение с браузером тоже должно распознавать эту команду, когда какое-то приложение у пользователя использует этот код. На эмуляторе как минимум есть одна такая программа «Browser», и теперь к ней добавилась наша вторая активность из первого приложения. На экране появится выбор из двух приложений.

А если удалить все альтернативные браузеры и оставить только вашу программу, то и выбора не будет. Ваш браузер станет основным. И если какое-то приложение захочет запустить веб-страницу указанным способом, то откроется ваша программа.

Небольшое замечание. Если заменить последнюю строчку на такую:

То в окне выбора программы вместо верхней строки «Open with» или её локального перевода появится ваша строка. Но не это главное. Если по каким-то причинам на устройстве не окажется ни одного браузера, то данный вариант кода не вызовет краха приложения, в отличие от первоначального варианта. Поэтому используйте предложенный вариант ради надёжности.

Источник

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

Источник

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

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

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:

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:

Источник

Читайте также:  Встроенный геймпад для андроид
Оцените статью