Android uri from string

Содержание
  1. URI (Uniform Resource Identifier)
  2. Координаты
  3. Номер телефона
  4. Контакты
  5. Android uri from string
  6. Summary
  7. Fields
  8. public static final Creator CREATOR
  9. public static final Uri EMPTY
  10. Public Methods
  11. public abstract Uri.Builder buildUpon ()
  12. public int compareTo (Uri other)
  13. public static String decode (String s)
  14. public static String encode (String s, String allow)
  15. public static String encode (String s)
  16. public boolean equals (Object o)
  17. public static Uri fromFile (File file)
  18. public static Uri fromParts (String scheme, String ssp, String fragment)
  19. public abstract String getAuthority ()
  20. public boolean getBooleanQueryParameter (String key, boolean defaultValue)
  21. public abstract String getEncodedAuthority ()
  22. public abstract String getEncodedFragment ()
  23. public abstract String getEncodedPath ()
  24. public abstract String getEncodedQuery ()
  25. public abstract String getEncodedSchemeSpecificPart ()
  26. public abstract String getEncodedUserInfo ()
  27. public abstract String getFragment ()
  28. public abstract String getHost ()
  29. public abstract String getLastPathSegment ()
  30. public abstract String getPath ()
  31. public abstract List getPathSegments ()
  32. public abstract int getPort ()
  33. public abstract String getQuery ()
  34. public String getQueryParameter (String key)
  35. public Set getQueryParameterNames ()
  36. public List getQueryParameters (String key)
  37. public abstract String getScheme ()
  38. public abstract String getSchemeSpecificPart ()
  39. public abstract String getUserInfo ()
  40. public int hashCode ()
  41. public boolean isAbsolute ()
  42. public abstract boolean isHierarchical ()
  43. public boolean isOpaque ()
  44. public abstract boolean isRelative ()
  45. public Uri normalizeScheme ()
  46. Полный список

URI (Uniform Resource Identifier)

URI — это специальный идентификатор, по которому можно определить абстрактный или физический ресурс. Самый понятный пример с URI — это обычная веб-страница. Возьмём к примеру страницу http://developer.alexanderklimov.ru/android/catshop/catshop.php. Данный адрес можно разбить на несколько частей:

  • Scheme — http
  • Scheme-specific part — //developer.alexanderklimov.ru/android/catshop/catshop.php
  • Path — /android/catshop/

У протокола http есть и другие параметры, которые рассматривать не будем. Существует также протокол ftp, имеющий свои параметры. Ниже вы увидите другие примеры. Главное здесь — возможность определить нахождение ресурса по представленным данным.

Допустим, мы хотим загрузить видеоматериал в компонент VideoView. Само видео может находиться в ресурсах программы или на SD-карте. С помощью URI мы можем подсказать программе, откуда следует загрузить файл.

Например, если видеофайл playcat.3gp находится в папке /res/raw, то получить адрес для загрузки можно следующим образом:

Если файл хранится на внешней карточке, то код будет следующим (опустим правильное определение имени карточки):

У компонента VideoView есть метод setVideoURI(URI uri), в котором нужно указать объект класса URI:

Посмотрим на другие примеры:

Координаты

Метод uri.getScheme() вернёт geo, а метод uri.getSchemeSpecificPart()54.354183,37.34011.

Номер телефона

В данном случае метод uri.getScheme() вернёт tel, а uri.getSchemeSpecificPart() — 1234578.

Контакты

URI также используется при работе с контент-провайдерами, в частности, с контактами.

Источник

Android uri from string

Immutable URI reference. A URI reference includes a URI and a fragment, the component of the URI following a ‘#’. Builds and parses URI references which conform to RFC 2396.

In the interest of performance, this class performs little to no validation. Behavior is undefined for invalid input. This class is very forgiving—in the face of invalid input, it will return garbage rather than throw an exception unless otherwise specified.

Summary

Nested Classes
Uri.Builder Helper class for building or manipulating URI references.
[Expand]
int CONTENTS_FILE_DESCRIPTOR Bit masks for use with describeContents() : each bit represents a kind of object considered to have potential special significance when marshalled.
int PARCELABLE_WRITE_RETURN_VALUE Flag for use with writeToParcel(Parcel, int) : the object being written is a return value, that is the result of a function such as » Parcelable someFunction() «, » void someFunction(out Parcelable) «, or » void someFunction(inout Parcelable) «.
Fields
CREATOR Reads Uris from Parcels.
EMPTY The empty URI, equivalent to «».
Public Methods

Fields

public static final Creator CREATOR

Reads Uris from Parcels.

public static final Uri EMPTY

The empty URI, equivalent to «».

Public Methods

public abstract Uri.Builder buildUpon ()

Constructs a new builder, copying the attributes from this Uri.

public int compareTo (Uri other)

Compares the string representation of this Uri with that of another.

public static String decode (String s)

Decodes ‘%’-escaped octets in the given string using the UTF-8 scheme. Replaces invalid octets with the unicode replacement character («\\uFFFD»).

Parameters
Returns
  • the given string with escaped octets decoded, or null if s is null

public static String encode (String s, String allow)

Encodes characters in the given string as ‘%’-escaped octets using the UTF-8 scheme. Leaves letters («A-Z», «a-z»), numbers («0-9»), and unreserved characters («_-!.

‘()*») intact. Encodes all other characters with the exception of those specified in the allow argument.

Parameters
s string to encode
allow set of additional characters to allow in the encoded form, null if no characters should be skipped
Returns
  • an encoded version of s suitable for use as a URI component, or null if s is null

public static String encode (String s)

Encodes characters in the given string as ‘%’-escaped octets using the UTF-8 scheme. Leaves letters («A-Z», «a-z»), numbers («0-9»), and unreserved characters («_-!.

‘()*») intact. Encodes all other characters.

Parameters
Returns
  • an encoded version of s suitable for use as a URI component, or null if s is null

public boolean equals (Object o)

Compares this Uri to another object for equality. Returns true if the encoded string representations of this Uri and the given Uri are equal. Case counts. Paths are not normalized. If one Uri specifies a default port explicitly and the other leaves it implicit, they will not be considered equal.

Parameters
o the object to compare this instance with.
Returns
  • true if the specified object is equal to this Object ; false otherwise.

public static Uri fromFile (File file)

Creates a Uri from a file. The URI has the form «file://». Encodes path characters with the exception of ‘/’.

Returns
Throws

public static Uri fromParts (String scheme, String ssp, String fragment)

Creates an opaque Uri from the given components. Encodes the ssp which means this method cannot be used to create hierarchical URIs.

Parameters
scheme of the URI
ssp scheme-specific-part, everything between the scheme separator (‘:’) and the fragment separator (‘#’), which will get encoded
fragment fragment, everything after the ‘#’, null if undefined, will get encoded
Returns
  • Uri composed of the given scheme, ssp, and fragment
Throws
See Also

public abstract String getAuthority ()

Gets the decoded authority part of this URI. For server addresses, the authority is structured as follows: [ userinfo ‘@’ ] host [ ‘:’ port ]

Examples: «google.com», «bob@google.com:80»

Returns
  • the authority for this URI or null if not present

public boolean getBooleanQueryParameter (String key, boolean defaultValue)

Searches the query string for the first value with the given key and interprets it as a boolean value. «false» and «0» are interpreted as false , everything else is interpreted as true .

Parameters
key which will be decoded
defaultValue the default value to return if there is no query parameter for key
Returns
  • the boolean interpretation of the query parameter key

public abstract String getEncodedAuthority ()

Gets the encoded authority part of this URI. For server addresses, the authority is structured as follows: [ userinfo ‘@’ ] host [ ‘:’ port ]

Examples: «google.com», «bob@google.com:80»

Returns
  • the authority for this URI or null if not present

public abstract String getEncodedFragment ()

Gets the encoded fragment part of this URI, everything after the ‘#’.

Returns
  • the encoded fragment or null if there isn’t one

public abstract String getEncodedPath ()

Gets the encoded path.

Returns
  • the encoded path, or null if this is not a hierarchical URI (like «mailto:nobody@google.com») or the URI is invalid

public abstract String getEncodedQuery ()

Gets the encoded query component from this URI. The query comes after the query separator (‘?’) and before the fragment separator (‘#’). This method would return «q=android» for «http://www.google.com/search?q=android».

Returns
  • the encoded query or null if there isn’t one

public abstract String getEncodedSchemeSpecificPart ()

Gets the scheme-specific part of this URI, i.e. everything between the scheme separator ‘:’ and the fragment separator ‘#’. If this is a relative URI, this method returns the entire URI. Leaves escaped octets intact.

Returns
  • the decoded scheme-specific-part

public abstract String getEncodedUserInfo ()

Gets the encoded user information from the authority. For example, if the authority is «nobody@google.com», this method will return «nobody».

Returns
  • the user info for this URI or null if not present

public abstract String getFragment ()

Gets the decoded fragment part of this URI, everything after the ‘#’.

Returns
  • the decoded fragment or null if there isn’t one

public abstract String getHost ()

Gets the encoded host from the authority for this URI. For example, if the authority is «bob@google.com», this method will return «google.com».

Returns
  • the host for this URI or null if not present

public abstract String getLastPathSegment ()

Gets the decoded last segment in the path.

Returns
  • the decoded last segment or null if the path is empty

public abstract String getPath ()

Gets the decoded path.

Returns
  • the decoded path, or null if this is not a hierarchical URI (like «mailto:nobody@google.com») or the URI is invalid

public abstract List getPathSegments ()

Gets the decoded path segments.

Returns
  • decoded path segments, each without a leading or trailing ‘/’

public abstract int getPort ()

Gets the port from the authority for this URI. For example, if the authority is «google.com:80», this method will return 80.

Returns
  • the port for this URI or -1 if invalid or not present

public abstract String getQuery ()

Gets the decoded query component from this URI. The query comes after the query separator (‘?’) and before the fragment separator (‘#’). This method would return «q=android» for «http://www.google.com/search?q=android».

Returns
  • the decoded query or null if there isn’t one

public String getQueryParameter (String key)

Searches the query string for the first value with the given key.

Warning: Prior to Jelly Bean, this decoded the ‘+’ character as ‘+’ rather than ‘ ‘.

Parameters
Returns
  • the decoded value or null if no parameter is found
Throws
UnsupportedOperationException if this isn’t a hierarchical URI
NullPointerException if key is null

public Set getQueryParameterNames ()

Returns a set of the unique names of all query parameters. Iterating over the set will return the names in order of their first occurrence.

Returns
Throws
UnsupportedOperationException if this isn’t a hierarchical URI

public List getQueryParameters (String key)

Searches the query string for parameter values with the given key.

Parameters
Returns
Throws
UnsupportedOperationException if this isn’t a hierarchical URI
NullPointerException if key is null

public abstract String getScheme ()

Gets the scheme of this URI. Example: «http»

Returns
  • the scheme or null if this is a relative URI

public abstract String getSchemeSpecificPart ()

Gets the scheme-specific part of this URI, i.e. everything between the scheme separator ‘:’ and the fragment separator ‘#’. If this is a relative URI, this method returns the entire URI. Decodes escaped octets.

Returns
  • the decoded scheme-specific-part

public abstract String getUserInfo ()

Gets the decoded user information from the authority. For example, if the authority is «nobody@google.com», this method will return «nobody».

Returns
  • the user info for this URI or null if not present

public int hashCode ()

Hashes the encoded string represention of this Uri consistently with equals(Object) .

Returns

public boolean isAbsolute ()

Returns true if this URI is absolute, i.e. if it contains an explicit scheme.

Returns
  • true if this URI is absolute, false if it’s relative

public abstract boolean isHierarchical ()

Returns true if this URI is hierarchical like «http://google.com». Absolute URIs are hierarchical if the scheme-specific part starts with a ‘/’. Relative URIs are always hierarchical.

public boolean isOpaque ()

Returns true if this URI is opaque like «mailto:nobody@google.com». The scheme-specific part of an opaque URI cannot start with a ‘/’.

public abstract boolean isRelative ()

Returns true if this URI is relative, i.e. if it doesn’t contain an explicit scheme.

Returns
  • true if this URI is relative, false if it’s absolute

public Uri normalizeScheme ()

Return an equivalent URI with a lowercase scheme component. This aligns the Uri with Android best practices for intent filtering.

For example, «HTTP://www.android.com» becomes «http://www.android.com»

All URIs received from outside Android (such as user input, or external sources like Bluetooth, NFC, or the Internet) should be normalized before they are used to create an Intent.

This method does not validate bad URI’s, or ‘fix’ poorly formatted URI’s — so do not use it for input validation. A Uri will always be returned, even if the Uri is badly formatted to begin with and a scheme component cannot be found.

Источник

Полный список

— узнаем, что такое Uri и Intent-атрибут data
— вызываем системные приложения (браузер, звонилка, карта)

Мы знаем, что Intent имеет атрибут action. С помощью этого атрибута обычно дается указание действия. Например, просмотр или редактирование. Но действие обычно совершается не просто так, а с чем-либо. Значит кроме указания действия, мы должны указывать на объект, с которым эти действия нужно произвести. Для этого Intent имеет атрибут data.

Один из способов присвоения значения этому атрибуту – метод setData (Uri data) у объекта Intent. На вход этому методу подается объект Uri.

Uri – это объект, который берет строку, разбирает ее на составляющие и хранит в себе эту информацию. Строка, конечно, должна быть не любая, а составлена в соответствии с этим документом RFC 2396. Uri имеет кучу методов, которые позволяют извлекать из распарсенной строки отдельные элементы.

Я создам объект Uri из строки, а в лог буду выводить название метода и (через двоеточие) значение, которое он возвращает. Например возьмем такую строку — http адрес:

Смотрим, чего нам возвращают методы:

uri.getScheme(): http
uri.getSchemeSpecificPart(): //developer.android.com/reference/android/net/Uri.html
uri.getAuthority(): developer.android.com
uri.getHost(): developer.android.com
uri.getPath(): /reference/android/net/Uri.html
uri.getLastPathSegment(): Uri.html

Понятия Scheme, Authority, Host, Path и пр. – взяты из RFC дока, ссылку на который я дал выше. Там можно найти их полное описание, понять что они означают и свериться с тем, что нам вернул Uri.

Рассмотрим еще примеры:

(Код, написанный выше, идет одной строкой на самом деле. Здесь идут пробелы вокруг @ из-за особенностей разметки)

uri.getScheme(): ftp
uri.getSchemeSpecificPart(): // Этот адрес электронной почты защищён от спам-ботов. У вас должен быть включен JavaScript для просмотра. :80/data/files
uri.getAuthority(): Этот адрес электронной почты защищён от спам-ботов. У вас должен быть включен JavaScript для просмотра. :80
uri.getHost(): google.com
uri.getPort(): 80
uri.getPath(): /data/files
uri.getLastPathSegment(): files
uri.getUserInfo(): bob

uri.getScheme(): geo
uri.getSchemeSpecificPart(): 55.754283,37.62002

Здесь уже получилось выделить только Scheme и SchemeSpecificPart.

Аналогично, получилось выделить только две части из строки.

Контакт из адресной книги

uri.getScheme(): content
uri.getSchemeSpecificPart(): //contacts/people/1
uri.getAuthority(): contacts
uri.getPath(): /people/1
uri.getLastPathSegment(): 1

В этом примере Scheme равен content. Это особый тип данных – Content Provider. Он позволяет любой программе давать доступ к своим данным, а другим программам – читать и менять эти данные. Эту тему мы рассмотрим позднее, и сами будем создавать такой тип данных.

Здесь можно посмотреть какие стандартные Uri поддерживаются.

Примеры показывают, что Uri можно создать из абсолютно разных строк: http-адрес, ftp-адрес, координаты, номер телефона, контакт из адресной книги.

Тип содержимого можно определить по Scheme. И этот же Scheme можно настроить в Intent Filter и отсеивать Intent, только с нужным нам типом данных в Uri, например только http. Этим мы еще займемся позднее, а пока сделаем простой пример, в котором будем формировать Intent с action и data, отправлять его и смотреть, что получится. Попробуем просмотреть следующее: http-адрес, координаты на карте и открыть окно набора номера.

Чтобы посмотреть координаты на карте, необходимо приложение Google Maps. Его нет в стандартных образах Android систем (тех, что вы в SDK Manager скачивали). Нужен образ, название которого начинается с «Google APIs»

Создайте AVD на платформе Google APIs с API Level 10. Назовите его на ваше усмотрение.

Создадим проект. Обратите внимание, используем платформу Google APIs версии 2.3.3

Project name: P0311_SimpleIntents
Build Target: Google APIs 2.3.3
Application name: SimpleIntents
Package name: ru.startandroid.develop.p0311simpleintents
Create Activity: MainActivity

Если у вас не получилось установить Google APIs, то создавайте проект как обычно — с платформой Android 2.3.3. Просто не будет работать вызов Google Maps в этом примере.

Сформируем экран main.xml

На экране три кнопки. Первая будет открывать веб-страницу, вторая — карту, третья – звонилку.

Пишем код в MainActivity.java:

Я использовал три разных способа создания Intent-а и задания его атрибутов.

В случае btnWeb я использовал конструктор Intent (String action, Uri uri). Он создает Intent и на вход сразу принимает action и data. Мы используем стандартный системный action – ACTION_VIEW. Это константа в классе Intent – означает, что мы хотим просмотреть что-либо. В качестве data мы подаем объект Uri, созданный из веб-ссылки: http://developer.android.com. И если попытаться описать словами наш код, то получится так: этот Intent означает, что мы хотим посмотреть содержимое этой ссылки и ищем Activity, которая могла бы нам помочь.

В случае btnMap использовался конструктор Intent(). Он просто создает Intent. А в следующих строках мы уже присваиваем ему атрибуты action и data. action – снова ACTION_VIEW, а в качестве data мы создаем Uri из пары координат — 55.754283,37.62002. Этот Intent означает, что мы хотим посмотреть на карте указанные координаты.

В случае btnCall используем конструктор Intent (String action). На вход ему сразу подается action, а data указывается позже. action в данном случае – ACTION_DIAL – открывает звонилку и набирает номер, указанный в data, но не начинает звонок. В data – помещаем Uri, созданный из номера телефона 12345.

Три этих способа приводят к одному результату — Intent с заполненными атрибутами action и data. Какой из них использовать — решать вам в зависимости от ситуации.

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

Также в файле манифеста приложения, на вкладке Permission добавьте элемент Uses Permission и справа в поле Name выберите android.permission.INTERNET. Это даст приложению доступ в интернет. Правда у меня почему-то и без этого все работает … Пока не понял почему.

Все сохраняем и запускаем приложение

Жмем кнопку Web,

открывается стандартный браузер и отображает содержимое страницы по ссылке

Возвращаемся, жмем Map. Отображается карта, которая показывает место, соответствующее указанным координатам.

Возвращаемся, жмем Call. Отображается стандартный экран набора номера и видим, что номер, который мы указывали в data, уже набран. Нам остается только нажать кнопку звонка.

Скорее всего, сейчас есть много вопросов типа «Что будет если … ». На некоторые из них сразу могу ответить и предлагаю вам поэкспериментировать в текущем приложении:

1) Что будет, если указать координаты без приставки geo:

Система ругнется, что не нашла подходящего Activity (см. логи). Т.к. в Activity карты настроен Intent Filter, который (как я думаю) настроен на data c Schema = geo.

Аналогично не сработает звонилка, если указать номер без приставки tel.

2) Что будет, если в координатах оставить geo, но координаты указать кривые?

Если мы попробуем посмотреть, например, такие координаты geo:a,b, то карта запустится, но скажет нам Unable to load the URL. Т.е. данные подошли по Schema, но оказались некорректными.

3) Что будет, если координаты указать верно, но action использовать не ACTION_VIEW, а ACTION_EDIT.

Получается, что мы хотим отредактировать место на карте заданное этими координатами. Но система говорит нам, что она не нашла такое Activity. Потому что приложение Google Maps ожидает Intent с action = ACTION_VIEW и оно сможет показать нам это место на карте. А на редактирование оно не подписывалось )

Необходимо понять, что все приложения в системе заточены под конкретные действия с конкретными типами данных. И если вы попробуете позвонить на адрес сайта, или открыть на карте номер телефона – то система просто не найдет приложения, способные на это.

На следующем уроке:

— пишем простой браузер

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Читайте также:  Безопасное хранилище андроид что это
Оцените статью