- Read NFC tag without specific application?
- 2 Answers 2
- Reading RFID with Android phones [closed]
- 7 Answers 7
- Advanced NFC
- In this document
- Working with Supported Tag Technologies
- Working with tag technologies and the ACTION_TECH_DISCOVERED intent
- Reading and writing to tags
- Using the Foreground Dispatch System
- Разработка NFC приложений для Android
- Архитектура технологии NFC
- Режим эмуляции NFC карты
- Пиринговый режим
- Режим записи/чтения
- Введение в разработку NFC под Android
- Пример 1. Разработка NFC приложения для чтения/записи меток.
- Пример 2. Разработка NFC-приложения, использующего карты MifareClassic
Read NFC tag without specific application?
I was wondering if there is any way to save a string of text (URL) to an NFC tag, let us say MIFARE or NTAG203, that can be read by other devices (smartphones) without the need of any special tag reading application.
I have tested several applications, e.g. Trigger for Android, and noticed that if the device reading the tag does not have the required application to read the data/instructions off the tag it still opens a URL that sends you to the Play Store to download that application.
So there must be a way to save some data readable by all/some NFC enabled phones. Simply put I want to create an applcation for Android that will write data to NFC tags and the data can be read/opened/executed by a random NFC enabled phone.
So is it possible to prepare an NFC tag that triggers some action on the reading device without requiring a specific application? What type of data could I write on an NFC tag with my app to achieve this?
2 Answers 2
First of all, in general, I agree with CommonsWare point of view that it’s always a «special» app that handles NFC events. However, when looking into Android, I would consider the various platform apps from AOSP as part of the Android system. Even though not all of them may be available on all devices.
Looking into Andrid 4.4+, the following data types are handled by such system apps:
- Browser: URIs with schemes «http:» and «https:».
- Contacts and Dialer: MIME types «text/vcard» and «text/x-vcard» for importing contacts.
- E-mail: URIs with scheme «mailto:»
In addition, if no other app handles a certain tag, NFC devices should(?) have the Tag app, that tries to handle various types (upon user confirmation):
- URIs with scheme «tel» will cause an ACTION_CALL intent to call the given number.
- URIs with schemes «sms»/»smsto» will cause an ACTION_SENDTO intent to start editing an SMS message.
- Other URIs should(?) be forwarded in ACTION_VIEW intents.
- MIME type records with type «text/x-vcard» (if not already handled) should be forwarded in ACTION_VIEW intents.
- The text message of Text RTD records (not text/* MIME types!) should be displayed in the Tag app. Unfortunately many stupid(!) NFC apps register for Text records, thus you will normally not get to the Tag app.
- MIME type records with type image/* (if image type is supported by Android) should be displayed in the Tag app.
Some records are handled by the NFC service itself (this should always be available on Android):
Источник
Reading RFID with Android phones [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 months ago .
I did enough research on reading RFID tags using Android phones(smart phones).
My understanding of this is that for NFC-enabled smart phones (Nexus S) it is possible to read RFID tags, but there are restrictions.
For non-NFC-enabled Androids we need a RFID reader to which we can communicate from Android using Bluetooth.
- What are the SDK which we use for reading RFID tag from Android Phone(NFC enabled)?
- If I have to read using Non NFC enabled phone, is there any standard reader available who provides SDK for development purpose?
7 Answers 7
NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.
You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.
I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.
If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.
You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I’m concerned):
1) Buy another Arduino Shield that supports RFID. I haven’t seen one that supports UHF so far.
2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.
Right now, I’m working in the second option but with iPhone.
First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power — which is why you see tap and go type usage.
The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.
HF — high frequency tags are what they use for «chipping» animals — cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.
UFH tags look similar to HF tags but have a read range of several feet.
Also HF tags come single read and multi read. UFH is exclusviely multi read.
Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.
But this is a function of the size of the antenna and how much power you can push through the reader.
As to the direct question about Android and RFID — the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices — Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.
The TSL line of readers is very popular because you don’t have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.
Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.
Источник
Advanced NFC
In this document
This document describes advanced NFC topics, such as working with various tag technologies, writing to NFC tags, and foreground dispatching, which allows an application in the foreground to handle intents even when other applications filter for the same ones.
Working with Supported Tag Technologies
When working with NFC tags and Android-powered devices, the main format you use to read and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support in parsing the message and delivering it in an NdefMessage when possible. There are cases, however, when you scan a tag that does not contain NDEF data or when the NDEF data could not be mapped to a MIME type or URI. In these cases, you need to open communication directly with the tag and read and write to it with your own protocol (in raw bytes). Android provides generic support for these use cases with the android.nfc.tech package, which is described in Table 1. You can use the getTechList() method to determine the technologies supported by the tag and create the corresponding TagTechnology object with one of classes provided by android.nfc.tech
Table 1. Supported tag technologies
Class | Description |
---|---|
TagTechnology | The interface that all tag technology classes must implement. |
NfcA | Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. |
NfcB | Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. |
NfcF | Provides access to NFC-F (JIS 6319-4) properties and I/O operations. |
NfcV | Provides access to NFC-V (ISO 15693) properties and I/O operations. |
IsoDep | Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. |
Ndef | Provides access to NDEF data and operations on NFC tags that have been formatted as NDEF. |
NdefFormatable | Provides a format operations for tags that may be NDEF formattable. |
The following tag technlogies are not required to be supported by Android-powered devices.
Table 2. Optional supported tag technologies
Class | Description |
---|---|
MifareClassic | Provides access to MIFARE Classic properties and I/O operations, if this Android device supports MIFARE. |
MifareUltralight | Provides access to MIFARE Ultralight properties and I/O operations, if this Android device supports MIFARE. |
Working with tag technologies and the ACTION_TECH_DISCOVERED intent
When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, the tag dispatch system tries to start an activity with the ACTION_TECH_DISCOVERED intent. The ACTION_TECH_DISCOVERED is also used when a tag with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag directly if the tag dispatch system could not parse it for you. The basic steps when working with tag technologies are as follows:
- Filter for an ACTION_TECH_DISCOVERED intent specifying the tag technologies that you want to handle. See Filtering for NFC intents for more information. In general, the tag dispatch system tries to start a ACTION_TECH_DISCOVERED intent when an NDEF message cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For more information on how this is determined, see The Tag Dispatch System.
- When your application receives the intent, obtain the Tag object from the intent:
- Obtain an instance of a TagTechnology , by calling one of the get factory methods of the classes in the android.nfc.tech package. You can enumerate the supported technologies of the tag by calling getTechList() before calling a get factory method. For example, to obtain an instance of MifareUltralight from a Tag , do the following:
Reading and writing to tags
Reading and writing to an NFC tag involves obtaining the tag from the intent and opening communication with the tag. You must define your own protocol stack to read and write data to the tag. Keep in mind, however, that you can still read and write NDEF data when working directly with a tag. It is up to you how you want to structure things. The following example shows how to work with a MIFARE Ultralight tag.
Using the Foreground Dispatch System
The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. Using this system involves constructing a few data structures for the Android system to be able to send the appropriate intents to your application. To enable the foreground dispatch system:
- Add the following code in the onCreate() method of your activity:
- Create a PendingIntent object so the Android system can populate it with the details of the tag when it is scanned.
- Declare intent filters to handle the intents that you want to intercept. The foreground dispatch system checks the specified intent filters with the intent that is received when the device scans a tag. If it matches, then your application handles the intent. If it does not match, the foreground dispatch system falls back to the intent dispatch system. Specifying a null array of intent filters and technology filters, specifies that you want to filter for all tags that fallback to the TAG_DISCOVERED intent. The code snippet below handles all MIME types for NDEF_DISCOVERED . You should only handle the ones that you need.
- Set up an array of tag technologies that your application wants to handle. Call the Object.class.getName() method to obtain the class of the technology that you want to support.
- Override the following activity lifecycle callbacks and add logic to enable and disable the foreground dispatch when the activity loses ( onPause() ) and regains ( onResume() ) focus. enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this). You also need to implement the onNewIntent callback to process the data from the scanned NFC tag.
See the ForegroundDispatch sample from API Demos for the complete sample.
Источник
Разработка NFC приложений для Android
Архитектура технологии NFC
NFC основана на RFID технологии с частотой 13.56 МГц и рабочей дистанцией до 10 см. Скорость обмена данными составляет до 424 кб/сек. По сравнению с другими коммуникационными технологиями, основным преимуществом NFC является быстрота и простота использования. На рисунке ниже видно расположение NFC среди других коммуникационных технологий.
Технология NFC имеет три режима: эмуляция NFC-карты, пиринговый режим и режим чтения/записи.
В режиме эмуляции карты NFC представляет собой аналог чипованной RFID карты со своим модулем безопасности, позволяющим защищать процесс покупки. В пиринговом режиме вы можете делиться информацией, например визитной карточкой, с другими NFC устройствами. В также можете устанавливать WiFi или Bluetooth соединения посредством NFC для передачи больших объемов данных. Режим чтения/записи предназначен для чтения или изменения NFC меток с помощью NFC устройств.
Каждый режим более подробно описан ниже.
Режим эмуляции NFC карты
NFC модуль обычно состоит из двух частей: NFC контроллера и элемента безопасности (ЭБ). NFC контроллер отвечает за коммуникации, ЭБ – за шифрацию и дешифрацию чувствительной к взлому информации.
ЭБ подключается к NFC контроллеру посредством шины SWP (Single Wire Protocol) или DCLB (Digital Contactless Bridge). Стандарты NFC определяют логический интерфейс между хостом и контроллером, позволяя им взаимодействовать через RF-поле. ЭБ реализуется с помощью встроенного приложения или компонента ОС.
Существует три варианта реализации ЭБ: можно встроить его в SIM-карту, SD-карту или в NFC чип.
Операторы связи, такие как CMCC (China Mobile Communication Corporation), Vodafone или AT&T обычно используют решение на SIM-карте, поощряя своих абонентов бесплатной заменой старых SIM-карт на новые, оснащенные NFC.
Пиринговый режим
Два NFC устройства могут легко взаимодействовать друг с другом напрямую, обмениваясь небольшими файлами. Для установления Bluetooth/WiFi соединения необходимо обменяться XML файлом специального формата. В этом режиме ЭБ не используется.
Режим записи/чтения
В данном режиме NFC устройство может читать и записывать NFC метки. Хорошим примером применения является чтение информации с оснащенных NFC «умных» постеров.
Введение в разработку NFC под Android
Android поддерживает NFC с помощью двух пакетов: android.nfc и android.nfc.tech.
Основными классами в android.nfc являются:
NfcManager: Устройства под Android могут быть использованы для управления любыми обнаруженными NFC адаптерами, но поскольку большинство Android устройств поддерживают только один NFC адаптер, NfcManager обычно вызывается с getDefaultAdapter для доступа к конкретному адаптеру.
NfcAdapter работает как NFC агент, подобно сетевому адаптеру на ПК. С его помощью телефон получает доступ к аппаратной части NFC для инициализации NFC соединения.
NDEF: Стандарты NFC определяют общий формат данных, называемый NFC Data Exchange Format (NDEF), способный хранить и передавать различные типы объектов, начиная с MIME и заканчивая ультра-короткими RTD-документами, такими как URL. NdefMessage и NdefRecord – два типа NDEF для определенных NFC форумом форматов данных, которые будут использоваться в коде-примере.
Tag: Когда устройство Android обнаруживает пассивный объект типа ярлыка, карты и т.д., он создает объект типа «метка», помещая его далее в целевой объект и в заключении пересылая в соответствующий процесс.
Пакет android.nfc.tech также содержит множество важных подклассов. Эти подклассы обеспечивают доступ к функциям работы с метками, включающими в себя операции чтения и записи. В зависимости от используемого типа технологий, эти классы разбиты на различные категории, такие как NfcA, NfcB, NfcF, MifareClassic и так далее.
Когда телефон со включенным NFC обнаруживает метку, система доставки автоматически создает пакет целевой информации. Если в телефоне имеется несколько приложений, способных работать с этой целевой информаций, пользователю будет показано окно с предложением выбрать одно из списка. Система доставки меток определяет три типа целевой информации, в порядке убывания приоритета: NDEF_DISCOVERED, TECH_DISCOVERED, TAG_DISCOVERED.
Здесь мы используем целевой фильтр для работы со всеми типами информации начиная с TECH_DISCOVERED до ACTION_TECH_DISCOVERED. Файл nfc_tech_filter.xml используется для всех типов, определенных в метке. Подробности можно найти в документации Android. Рисунок ниже показывает схему действий при обнаружении метки.
Пример 1. Разработка NFC приложения для чтения/записи меток.
Следующий пример показывает функции чтения/записи NFC метки. Для того, чтобы получить доступ к аппаратной части NFC и корректно обрабатывать NFC информацию, объявите эти позиции в файле AndroidManifest.xml.
Минимальную версию SDK, которую должно поддерживать ваше приложение — 10, объявите об этом в файле AndroidManifest.xml
Следующий целевой вызов демонстрирует функцию чтения. Если широковещательное сообщение системы равняется NfcAdapter.ACTION_TAG_DISCOVERED, тогда вы можете считать информацию и показать ее.
Следующий код демонстрирует функцию записи. Перед тем, как определить значение mytag, вы должны убедиться, что метка определена и только потом вписать в нее свои данные.
В зависимости от прочитанной информации вы можете выполнить дополнительные действия, такие как запуск какого-либо задания, переход по ссылке и т.д.
Пример 2. Разработка NFC-приложения, использующего карты MifareClassic
В этом примере для чтения мы будем использовать карты MifareClassic и соответствующий им тип метки. Карты MifareClassic широко используются для различных нужд, таких как идентификация человека, автобусный билет и т.д. В традиционной карте MifareClassic область хранения разбита на 16 зон, в каждой зоне 4 блока, и каждый блок может хранить 16 байт данных.
Последний блок в зоне называется трейлером и используется обычно для хранения локального ключа чтения/записи. Он содержит два ключа, А и В, 6 байт длиной каждый, по умолчанию забитые 00 или FF, в зависимости от значения MifareClassic.KEY_DEFAULT.
Для записи на карту Mifare вы, прежде всего, должны иметь корректное значение ключа (что играет защитную роль), а также успешно пройти аутентификацию.
Пример того, как читать карту MifareClassic:
Источник