Android browser share intent

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

Источник

Sharing Content with Intents

Intents allow us to communicate data between Android apps and implicit intents can also accept actions. One of those actions is the ACTION_SEND command which indicates we want to send data across apps. To send data, all you need to do is specify the data and its type, and the system will identify compatible receiving activities and display them to the user.

Читайте также:  Клавиатура языки ввода андроид

Sending and receiving data between applications with intents is most commonly used for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.

You can send content by invoking an implicit intent with ACTION_SEND .

To send images or binary data:

Sending URL links should simply use text/plain type:

In certain cases, we might want to send an image along with text. This can be done with:

Sharing multiple images can be done with:

See this stackoverflow post for more details.

Note: Facebook does not properly recognize multiple shared elements. See this facebook specific bug for more details and share using their SDK.

Facebook doesn’t work well with normal sharing intents when sharing multiple content elements as discussed in this bug. To share posts with facebook, we need to:

  1. Create a new Facebook app here (follow the instructions)
  2. Add the Facebook SDK to your Android project
  3. Share using this code snippet:

You may want to send an image that were loaded from a remote URL. Assuming you are using a third party library like Glide, here is how you might share an image that came from the network and was loaded into an ImageView. There are two ways to accomplish this. The first way, shown below, takes the bitmap from the view and loads it into a file.

and then later assuming after the image has completed loading, this is how you can trigger a share:

Make sure to setup the «SD Card» within the emulator device settings:

Note that if you are using API 24 or above, see the section below on using a FileProvider to work around new file restrictions.

If you are targeting Android API 24 or higher, private File URI resources (file:///) cannot be shared. You must instead wrap the File object as a content provider (content://) using the FileProvider class.

First, you must declare this FileProvider in your AndroidManifest.xml file within the tag:

Next, create a resource directory called xml and create a fileprovider.xml . Assuming you wish to grant access to the application’s specific external storage directory, which requires requesting no additional permissions, you can declare this line as follows:

Finally, you will convert the File object into a content provider using the FileProvider class:

If you see a INSTALL_FAILED_CONFLICTING_PROVIDER error when attempting to run the app, change the string com.codepath.fileprovider in your Java and XML files to something more unique, such as com.codepath.fileprovider.YOUR_APP_NAME_HERE .

Note that there are other XML tags you can use in the fileprovider.xml , which map to the File directory specified. In the example above, we use Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) , which corresponded to the XML tag in the declaration with the Pictures path explicitly specified. Here are all the options you can use too:

XML tag Corresponding storage call When to use
Context.getFilesDir() data can only be viewed by app, deleted when uninstalled ( /data/data/[packagename]/files )
Context.getExternalFilesDir() data can be read/write by the app, any apps granted with READ_STORAGE permission can read too, deleted when uninstalled ( /Android/data/[packagename]/files )
Context.getCacheDir() temporary file storage
Environment.getExternalStoragePublicDirectory() data can be read/write by the app, any apps can view, files not deleted when uninstalled
Context.getExternalCacheDir() temporary file storage with usually larger space

If you are using API 23 or above, then you’ll need to request runtime permissions for Manifest.permission.READ_EXTERNAL_STORAGE and Manifest.permission.WRITE_EXTERNAL_STORAGE in order to share the image as shown above since newer versions require explicit permisions at runtime for accessing external storage.

Note: There is a common bug on emulators that will cause MediaStore.Images.Media.insertImage to fail with E/MediaStore﹕ Failed to insert image unless the media directory is first initialized as described in the link.

This is how you can easily use an ActionBar share icon to activate a ShareIntent. The below focuses on the support ShareActionProvider for use with AppCompatActivity .

Note: This is an alternative to using a sharing intent as described in the previous section. You either can use a sharing intent or the provider as described below.

First, we need to add an ActionBar menu item in res/menu/ in the XML specifying the ShareActionProvider class.

Next, get access to share provider menu item in the Activity so we can attach the share intent later:

Note: ShareActionProvider does not respond to onOptionsItemSelected() events, so you set the share action provider as soon as it is possible.

Now, once you’ve setup the ShareActionProvider menu item, construct and attach the share intent for the provider but only after image has been loaded as shown below using the RequestListener for Glide .

Note: Be sure to call attachShareIntentAction method both inside onCreateOptionsMenu AND inside the onResourceReady for Glide to ensure that the share attaches properly.

We can use a similar approach if we wish to create a share action for the current URL that is being loaded in a WebView:

Check out the official guide for easy sharing for more information.

Источник

Android Share Intent Example for URL, Text or Image

Today I’m going to give you an android share intent example that you can use to enable your app to share contents such as URL or text and Image to other apps installed in your Android device like Facebook, Twitter, Messaging, Instagram, Evernote, etc.. Example uses of this code include:

You are building an app that browses a certain website or URL.

Your app generates an image that a user can share.

Android Share Intent Example Step by Step

Step 1: Prepare XML Layout, we’ll have activity_main.xml

Step 2: Inside the onCreate method of MainActivity.java, put the buttons and OnClickListener handlers.

Step 3: As you’ve noticed, we have shareTextUrl() method that will be triggered every time the user clicks on the “Share Text or URL” button.

Step 4: We also have shareImage() method for sharing images. It is triggered when the user clicks on the “Share Image” button.

Complete MainActivity.java code:

Please note that when you use the setType() method, you are enabling Android to filter what apps can share your content. For example, you are sharing a text or URL, the appropriate apps to be shown can be Facebook, Messaging or Email. If you are sharing an image, proper apps can be Instagram, Snapseed or Picasa.

Today’s code output screenshots

Share Text or URL button was touched. Take note of the apps on the list.

User chose to share to Facebook

“Share Image” button was touched. Apps was different on the list.

User chose to share with Gmail. Our image was attached.

User chose to share to Snapseed.

If you have any suggestions to improve this post, please drop it in the comments section below! I’ll be glad to update this post for further improvement. Thanks for reading our Android Share Intent Example!

Источник

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» или её локального перевода появится ваша строка. Но не это главное. Если по каким-то причинам на устройстве не окажется ни одного браузера, то данный вариант кода не вызовет краха приложения, в отличие от первоначального варианта. Поэтому используйте предложенный вариант ради надёжности.

Источник

Читайте также:  Баланс для наушников андроид
Оцените статью