6
Topics covered NFC NFC NDEF NDEF NFC Foreground dispatch NFC Foreground dispatch NFC payload NFC payload NFC filter NFC filter Home » androd » ndef » nfc » tag » First steps with NFC in Android FIRST STEPS WITH NFC IN ANDROID PUBBLICATO DA FRANCESCO AZZOLA IN ANDROD, NDEF, NFC, TAG - ON MARCH 8, 2015 - NO COMMENTS This post describes how to use NFC in Android. The NFC technology stands for Near Field Communication and you can nd the specication at NFC Forum. In this rst post, we will analyse some basic aspects of NFC and we will describe how we can implement an app in Android that handles NFC tags. If you want to experiment NFC, there are several web site where you can buy NFC with a few euro. NFC can be used in dierent situation: we can use it to turn on our Wiwhen we are at home or launch task actions and so on. We will focus our attention on NDEF data that is a special type of NFC tag. There are some basic steps we have to follow before using the NFC. NFC Filter NFC Filter When we use NFC tag,, the rst thing we want is our app is notied when we get near a NFC tag. To this purpose we use a intent lter. Android SDK provides three dierent lter that we can use with dierent level of priority: ACTION_NDEF_DISCOVERED ACTION_TECH_DISCOVERED ACTION_TAG_DISCOVERED We focus our attention on ACTION_NDEF_DISCOVERED, that has the highest level of priority. As said, our goal is being notied when the smart phone is near a NFC tag and, if we have only this app installed and capable to handle this NFC tag, we want that the app starts immediately. To do it, we register the lter in the Manifest.xml: At line 6 we register our app so that it can be notied with ACTION_NDEF_DISCOVERED . We can use dierent types of lter, in this example (at line 8) we used mime type. In other word when a NFC tag NDEF is discovered and it has a mime type text/plain then our app will be started. We can lter using several mime types not only text/pain. We can, moreover, use other type of lters like android:scheme to lter using the protocol or using a string pattern. NFC Foreground Dispatch NFC Foreground Dispatch 28 2 Like Like 1 2 3 4 5 6 7 8 9 10 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.survivingwithandroid.nfc" > .... <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain"/> </intent-filter> <manifest> ? SURVIVING W/ ANDROID ANDROID DEVELOPMENT BLOG TUTORIALS ABOUT ANDROID DEV TOPICS Search here.... ! " # + %

Android NFC

Embed Size (px)

Citation preview

Page 1: Android NFC

Topics covered

NFCNFCNDEFNDEFNFC Foreground dispatchNFC Foreground dispatchNFC payloadNFC payloadNFC filterNFC filter

Home » androd » ndef » nfc » tag » First steps with NFC in Android

FIRST STEPS WITH NFC IN ANDROIDPUBBLICATO DA FRANCESCO AZZOLA IN ANDROD, NDEF, NFC, TAG - ON MARCH 8, 2015 - NO COMMENTS

This post describes how to use NFC in Android. The NFC technology stands

for Near Field Communication and you can find the specification at NFC

Forum. In this first post, we will analyse some basic aspects of NFC and we

will describe how we can implement an app in Android that handles NFC

tags.

If you want to experiment NFC, there are several web site where you can

buy NFC with a few euro.

NFC can be used in different situation: we can use it to turn on our Wifi when we are at home or launch task

actions and so on.

We will focus our attention on NDEF data that is a special type of NFC tag.

There are some basic steps we have to follow before using the NFC.

NFC FilterNFC FilterWhen we use NFC tag,, the first thing we want is our app is notified when

we get near a NFC tag. To this purpose we use a intent filter. Android SDK

provides three different filter that we can use with different level of priority:

ACTION_NDEF_DISCOVERED

ACTION_TECH_DISCOVERED

ACTION_TAG_DISCOVERED

We focus our attention on ACTION_NDEF_DISCOVERED, that has the highest level of priority. As said, our

goal is being notified when the smart phone is near a NFC tag and, if we have only this app installed and

capable to handle this NFC tag, we want that the app starts immediately. To do it, we register the filter in the

Manifest.xml:

At line 6 we register our app so that it can be notified with ACTION_NDEF_DISCOVERED . We can use

different types of filter, in this example (at line 8) we used mime type. In other word when a NFC tag NDEF is

discovered and it has a mime type text/plain then our app will be started. We can filter using several mime

types not only text/pain. We can, moreover, use other type of filters like android:scheme to filter using the

protocol or using a string pattern.

NFC Foreground DispatchNFC Foreground Dispatch

28 2LikeLike

123456789

10

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.survivingwithandroid.nfc" > .... <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain"/> </intent-filter><manifest>

?

SURVIVING W/ ANDROIDANDROID DEVELOPMENT BLOG TUTORIALS ABOUT ANDROID DEV TOPICS

Search here.... ! " # + %

Page 2: Android NFC

Filtering with intents works if our app is not in foreground. If our app is running in foreground, it won't be

notified, if move our smart phone near a NFC tag. In this case we have to use a different technique called

NFC Foreground dispatch. The first step is defining in our code the intent filter (as we did in the

manifest.xml):

Now we have to register our filter, and we do it in onResume method, in this way:

We should, also, remember to disable foreground dispatch as soon as the app gets in background and the

best place to do it is in onPause method.

where nfcAdpt is the NFC Adapter.

Handle NFC Using NFCAdapterHandle NFC Using NFCAdapterOnce we created our filters, we have to interact with the NFC component in our smart phone. For this

purpose, we use NfcAdapter, provided by Android SDK. Using this class, we can check, for example, if the

NFC is supported by our smart phone or if the NFC is turned on or off:

NFC Data: PayloadNFC Data: PayloadOnce we know how to handle NFC tag, we want to read the tag content. There are several type of content

defined in NFC specs:

NFC Forum well-known typeMedia-typeAbsolute URINFC Forum external type

Each type has it is own payload. Generally speaking, a NFC NDEF data is composed by a Message. A message

can contain one or more records. Each record is made by an header and a payload (the real information).

By now, if we want to read the data inside a NFC NDEF tag we can use:

123456789

10111213141516171819

@Overrideprotected void onCreate(Bundle savedInstanceState) { ... Intent nfcIntent = new Intent(this, getClass()); nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); nfcPendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0); IntentFilter tagIntentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { tagIntentFilter.addDataType("text/plain"); intentFiltersArray = new IntentFilter[]{tagIntentFilter}; } catch (Throwable t) { t.printStackTrace(); }}

123456789

protected void onResume() { super.onResume(); nfcAdpt.enableForegroundDispatch( this, nfcPendingIntent, intentFiltersArray, null); handleIntent(getIntent()); }

12345

@Overrideprotected void onPause() { super.onPause(); nfcAdpt.disableForegroundDispatch(this);}

123456789

1011121314

@Overrideprotected void onCreate(Bundle savedInstanceState) { ... nfcAdpt = NfcAdapter.getDefaultAdapter(this); // Check if the smartphone has NFC if (nfcAdpt == null) { Toast.makeText(this, "NFC not supported", Toast.LENGTH_LONG).show(); finish(); } // Check if NFC is enabled if (!nfcAdpt.isEnabled()) { Toast.makeText(this, "Enable NFC before using the app", Toast.LENGTH_LONG).show(); }}

?

?

?

?

Page 3: Android NFC

Android Text to Speech(TTS)

NFC Android: ReadNDEF Tag

Android Text to Speech(TTS)

NFC Android: ReadNDEF Tag

RELATED POSTS :

RELATED POSTS :

In the next post, we will describe how to read different NDEF types and how to extract information from the

tag.

If you want to know how to read look at NFC - Read NDEF Tag.

ETICHETTE: ANDROD, NDEF, NFC, TAG

123456789

101112131415161718192021222324252627282930

@Override public void onNewIntent(Intent intent) { Log.d("Nfc", "New intent"); getTag(intent); } private void getTag(Intent i) { if (i == null) return ; String type = i.getType(); String action = i.getAction(); List<ndefdata> dataList = new ArrayList<ndefdata>(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Log.d("Nfc", "Action NDEF Found"); Parcelable[] parcs = i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); for (Parcelable p : parcs) { recNumberTxt.setText(String.valueOf(numRec)); NdefRecord[] records = msg.getRecords(); for (NdefRecord record: records) { short tnf = record.getTnf(); // Here we handle the payload } } } }</ndefdata></ndefdata>

227 66Google + 1 26DZone 106Reddit 1

?

Page 4: Android NFC

If you like my work and want to help me tokeep this blog free, please support me clicking

on the banner.

Help me to share this blog and give +1 clickingbelow

407

FOLLOW MEFOLLOW ME

ARCHIVIO BLOGARCHIVIO BLOG

▼ ▼ 20152015 (3)

▼ ▼ MarchMarch (2)

NFC Android: Read NDEF TagNFC Android: Read NDEF Tag

First steps with NFC in AndroidFirst steps with NFC in Android

► ► FebruaryFebruary (1)

► ► 20142014 (26)

► ► 20132013 (32)

► ► 20122012 (19)

SUPPORT THIS BLOGSUPPORT THIS BLOG

Newer Post Older PostHome

++ &&

Page 5: Android NFC

POPULAR POSTSPOPULAR POSTS

Android ListView – Tutorial and basic exampleAndroid ListView – Tutorial and basic example

Android ListView : Custom Filter and Filterable interfaceAndroid ListView : Custom Filter and Filterable interface

Android HTTP Client: GET, POST, Download, Upload, MultipartAndroid HTTP Client: GET, POST, Download, Upload, Multipart

RequestRequest

Android weather app: JSON, HTTP and OpenweathermapAndroid weather app: JSON, HTTP and Openweathermap

Android Fragment transaction: FragmentManager and BackstackAndroid Fragment transaction: FragmentManager and Backstack

Android SlidingPaneLayout: TutorialAndroid SlidingPaneLayout: Tutorial

FOLLOW SWAFOLLOW SWA

POST PIÙ POPOLARIPOST PIÙ POPOLARI

Topics covered Android ListViewSimpleAdapter ...

In the previous post we showed theway we can...

© 2012-2015 Survivingwithandroid.com

All Rights Reserved. Reproduction without explicitpermission is prohibited.

FOLLOW SWA BY EMAILFOLLOW SWA BY EMAIL

CHECK MY APPCHECK MY APPCATEGORIES

' Android ListView – Tutorial andbasic example

'

' Android ListView : Custom Filter andFilterable interface

'

Android Blog' Contact me'

About Me'

Email address... Submit

android UI ListView tutorial android

Page 6: Android NFC

Topics covered HTTP connectionPost request ...

Topics covered How to developweather app ...

Topics covered Android FragmentFragment...

Topics covered AndroidSlidingPaneLayout ...

Topics covered Android ListViewArray Adapter ...

Topics covered AndroidSwipeRefreshLayout ...

In this post i want to analyze how touse ListView ...

Topics covered Android WeatherApp Yahoo...

' Android HTTP Client: GET, POST,

Download, Upload, MultipartRequest

'

' Android weather app: JSON, HTTPand Openweathermap

'

' Android Fragment transaction:FragmentManager and Backstack

'

' Android SlidingPaneLayout: Tutorial'

' Android ListView : Custom Adapterand Layout

'

' Android SwipeRefreshLayoutTutorial

'

' Android ListView withSectionIndexer and fast scroll

'

' Android Weather app Tutorial: Stepby Step guide (Part 2)

'

weather http Fragment Adapter android studioapp actionbar activity android volley custom view

eclipse json weather aar adt aidl androd

android app

tutorial android service animation apache app tutorial

asynctask client custom adapter design free gradle

intent intentservice ipc layout market material design

navigation nfc onTouchEvent openweathermap os x

peg board recyclerview remote service sensor service

slidingpanelayout uml volley weather app xml parser

ExpandableListView Filter OnClickListener SimpleAdapter

account achartengine android bound service

android

broadcastreceiver android camera android chart

android

html parsing android library android location api

android

nfc android torch app android wear apn

autocompletetextview avd back button barometer

bluetooth board bound service broadcast receiver button

camera camera flash cardview chart client lib

consume

service consume webservice custom component denisty

deserialization. diagram drive drop down navigation

emulator endless adapter error example face face detect

face recognition flash light floating action button forecast

fragments free app genymotion google haxm

high pass

filter http post import library inter process coimmunication

java jsoup lib link location locationManager ltiple screen

mac maven central menu money motionevent

multipart

request navigation drawer ndef ndef text network

opensource orbitix parcelable parse parser pitch plugin

process project structure promoted actions publish maven

pull-to-refresh restful resultreceiver rtd save layout sdk

sensorlistener sensormanager serialization

shake to

refresh share smart poster source code sphero sphero API

start service stats swiperefreshlayout tab tag text to speech

toolbar tts use case user interface view holder viewpager

voice webservice well known type xml yahoo weather

provider

© Copyright 2013 Surviving W/ Android - All Rights Reserved - Distributed By Gooyaabi Templates | Powered By Blogger

Template by Kang Ismet Published by GBTemplatesTemplate by Kang Ismet Published by GBTemplates