Open browser with url android

Kotlin Android – Open URL separately in Browser Activity

Open URL from Android Application in Default Browser

In an Android Application, it may be necessary to open a URL separately in a browser. The task of opening a URL can be triggered by any action performed on Views using Action Listeners.

In this tutorial, we shall look into an application, where we click a button, and a URL is opened in a browser window.

From the following screenshot, when user clicks on the button, a new Browser Activity is displayed over this Android Application, with the URL specified for that page.

Open URL from Android Application in Default Browser

To open an URI in a browser window separately, use android.content.Intent.ACTION_VIEW . ACTION_VIEW is used to display data to the user using the most reasonable presentation. For example, when used on a mailto, ACTION_VIEW opens a mail compose window; and when used on tel: , ACTION_VIEW displays call dialer.

Following are the detailed steps to create ACTION_VIEW for opening a URL.

Step 1: Create an Intent for ACTION_VIEW.

Step 2: Set Uri as data for the intent.

Step 3: Start Activity with the intent.

Example – Android Application to Open URL in Default Browser

Create an Android Project and replace the following layout file, activity_main.xml, and MainActivity.kt file.

activity_main.xml

MainActivity.kt

Run this Android Application, and click on any of the buttons, to open the respective URL separately in default Browser activity.

Conclusion

In this Kotlin Android Tutorial, we learned how to open URL from Android Application in default browser.

Источник

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:

Читайте также:  Что такое abd драйвера для андроид

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 из моего приложения?

Как открыть URL из кода во встроенном веб-браузере, а не в моем приложении?

Я попытался это:

но я получил исключение:

28 ответов:

это прекрасно работает для меня.

Что касается отсутствующего «http: / /» я бы просто сделал что-то вроде этого:

Я бы также, вероятно, предварительно заполнил ваш EditText, что пользователь вводит URL-адрес с помощью » http://».

распространенный способ добиться этого заключается в следующем коде:

это может быть изменено на короткую версию кода .

самый короткий! :

удачи в кодировании!

разница заключается в использовании Intent.ACTION_VIEW а не строка «android.intent.action.VIEW»

Простой Ответ

как это работает

пожалуйста, взгляните на конструктор Intent :

вы можете пройти android.net.Uri экземпляр для 2-го параметра, и новое намерение создается на основе данного url-адреса данных.

а потом, просто позвоните startActivity(Intent intent) чтобы начать новую деятельность, которая в комплекте с намерением с помощью заданный URL.

мне нужно if проверить заявление?

да. Элемент docs говорит:

если на устройстве нет приложений, которые могут получить неявное намерение, ваше приложение аварийно завершит работу при вызове startActivity(). Чтобы сначала убедиться, что приложение существует для получения намерения, вызовите resolveActivity() для объекта Intent. Если результат не равен нулю, есть по крайней мере одно приложение, которое может обрабатывать намерение, и его можно безопасно вызвать startActivity(). Если результат равен нулю, вы не должны использовать intent и, если это возможно, вы должны отключить функцию, которая вызывает intent.

бонус

вы можете написать в одной строке при создании экземпляра Intent, как показано ниже:

или если вы хотите, то веб-браузера в вашей деятельности, то делай так:

и если вы хотите использовать управление зумом в браузере, то вы можете использовать:

Если вы хотите показать пользователю Диалог со всем списком браузера, чтобы он мог выбрать предпочтительный, вот пример кода:

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

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

Читайте также:  Под что форматировать флешку для андроид

другой вариант в URL загрузки в том же приложении с помощью Webview

вы также можете пойти этим путем

в Манифесте не забудьте добавить разрешение в интернет.

Webview можно использовать для Загрузки Url-адреса в приложении. URL-адрес может быть предоставлен от пользователя в текстовом представлении или вы можете жестко его закодировать.

также не забывайте разрешения на интернет в AndroidManifest.

внутри в вашем блоке try вставьте следующий код, Android Intent использует непосредственно ссылку в скобках URI(Uniform Resource Identifier), чтобы определить местоположение вашей ссылки.

вы можете попробовать это:

хром пользовательские вкладки теперь доступны:

первым шагом является добавление библиотеки поддержки пользовательских вкладок в сборку.файл gradle:

и затем, чтобы открыть пользовательскую вкладку chrome:

ответ MarkB — Это верно. В моем случае я использую Xamarin, и код для использования С C# и Xamarin:

простой, просмотр веб-сайта с помощью намерения,

используйте этот простой код для просмотра вашего сайта в android-приложении.

добавить разрешение интернета в файл манифеста,

проверить, является ли URL-адрес является правильным. Для меня было нежелательное пространство перед url.

поместите код ниже в глобальный класс

на основе ответа от Марка B и комментариев ниже:

android.webkit.URLUtil имеет способ guessUrl(String) работает отлично (даже с file:// или data:// ) С Api level 1 (Android 1.0). Используйте как:

Регистрация полностью guessUrl код для получения дополнительной информации.

xml код: —

этот способ использует метод, позволяющий вводить любую строку вместо фиксированного ввода. Это позволяет сохранить некоторые строки кода, если они используются многократно, так как для вызова метода требуется всего три строки.

использование этого метода делает его универсальным. Он не должен быть помещен в определенную деятельность, так как вы можете использовать его следующим образом:

или если вы хотите запустить его вне действия, вы просто вызываете startActivity на действие пример:

как видно в обоих этих блоках кода есть нулевая проверка. Это так, как он возвращает null, если нет приложения для обработки намерения.

этот метод по умолчанию использует HTTP, если протокол не определен, так как есть веб-сайты, у которых нет сертификата SSL(что вам нужно для подключения HTTPS), и они перестанут работать, если вы попытаетесь использовать HTTPS, и его там нет. Любой веб-сайт все еще может принудительно перейти на HTTPS, поэтому эти стороны приземляют вас на HTTPS в любом случае

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

хорошо, я проверил каждый ответ, но какое приложение имеет deeplinking с тем же URL, который пользователь хочет использовать?

Источник

How to Open an Android App from the Browser

Alex Austin

January 8th, 2018

Opening an installed app from a browser is often referred to as “deep linking”, and with this guide you’ll learn how to deep link into your Android app for yourself. We’ll focus exclusively on how to trigger an app open from a website page, rather than from the click of a link inside other apps. For a more detailed look at all of the different deep linking standards required for complete Android coverage, please see our Android deep linking series: Part 1 , Part 2 , Part 3 , and Part 4 .

Android is, by far, one of the most fragmented platforms that developers have ever had to manage, due to Google’s decision to force device manufacturers to be responsible for porting the OS, which requires backwards compatibility and support of a multitude of devices. In this ecosystem, we, the app developers, are left to pick up the pieces. Deep linking on Android is unfortunately no different—over the years, we’ve seen a plethora of technical requirements that must be used depending on the circumstance and context of the user.

Читайте также:  Maratische android phone sms codes что это

Note that Branch will implement all of this complexity for you, host the deep links, and even give you robust analytics behind clicks, app opens, and down funnel events. You can play around with Branch links for free by signing up here . We highly recommend using our tools instead of trying to rebuild them from scratch, since we give them all away for free.

Overview of Changes

There are two places where changes will need to be made in order to successfully open your Android app: your website and your Android app. You can find the details of each change in the corresponding sections below.

Adding Support for URI Schemes to Your App

A URI scheme can be any string without special characters, such as http , pinterest , fb or myapp . Once registered, if you append :// to the end (e.g. pinterest://) and click this link, the Pinterest app will open up. If the Pinterest app is not installed, you’ll see a ‘Page Not Found’ error.

It is simple to configure your app for a URI scheme. To start, you need to pick an Activity within your app that you’d like to open when the URI scheme is triggered, and register an intent filter for it. Add the following code within the tag within your manifest that corresponds to the Activity you want to open.

You can change your_uri_scheme to the URI scheme that you’d like. Ideally, you want this to be unique. If it overlaps with another app’s URI scheme, the user will see an Android chooser when clicking on the link. You see this often when you have multiple browsers installed, as they all register for the http URI.

Next, you’ll want to confirm that your app was opened from the URI scheme. To handle the deep link in the app, you simply need to grab the intent data string in the Activity that was opened via the click. Below is an example:

From here, you’ll need to do string parsing to read the values appended the URI scheme that will be very specific to your use case and implementation.

Adding Javascript to Your Website to Open Your App

Now that your Android app is ready to be triggered from a URI scheme, the next part is simple. You merely need to add some Javascript to your website that will auto trigger your app open. The function below, triggerAppOpen , will attempt to open your app’s URI scheme once you replace your_uri_scheme with the one you added in the manifest above.

You could call triggerAppOpen into window.onload if you wanted to do it on page load, or you could make it the onclick of a link somewhere on your site. Either works and the you’ll get the intended results.

Android is incredibly complicated, and there are edge cases everywhere. You’ll think everything is going well until you get that one user complaining that his links aren’t working on Facebook while running Android 4.4.4. That’s why you should use a tool like Branch—to save you this nightmare and ensure that your links work everywhere. Be sure to request a Branch demo if you’re interested in learning more.

Источник

Оцените статью