WEBdeBS NFC Presentation

Post on 05-Dec-2014

1.140 views 3 download

description

Presentation about NFC technology and developing Android applications using it.

Transcript of WEBdeBS NFC Presentation

NFC Programming in Android

Ishan Fernando@ifdo

i.fernando@myti.it

Myti s.r.l.www.myti.it

NFC

• Comunicazione contactless• Nuova interazione utente • Sicurezza

NFC (Near Field Communication)

NFC (Near Field Communication)

• E' una tecnologia wireless a corto raggio (< 10cm)• Si opera alla frequenza di 13,56MHz• Può raggiungere una velocità di trasmissione massima di

424 kbit/s

NFC (Near Field Communication)

E' una evoluzione di RFID (Radio Frequency Identification)

RFID vs NFC

RFID NFC

estenzione di RFID

distanze lunghe (3 ~ 100m) distanze corte (< 10cm)

qualsiasi frequenza 13.56 MHz

usa nei vari ambiti usa nellʼambito di sicurezza

nei celluari

Storia

NDEF (NFC Data Exchange Format)

NDEF è un formato di incapsulamento dei messaggi (dati) per scambiare informazioni via NFC.

NDEF (NFC Data Exchange Format)

Questo formato consente di scambiare informazioni • tra due NFC Forum Devices • tra un NFC Forum Device e un NFC Forum Tag.

active modepassive mode

NDEF (NFC Data Exchange Format)

Message = n * Records

Records = Type +Size + 

Payload (binary data)

NDEF (NFC Data Exchange Format)

I messaggi NDEF possono essere di tre tipi : 

URI il contenuto è un link

MIME il contenuto è specificato da un mime type

NFC-specific types utilizzi specifici per diverse tecnologie

http://www.nfc-forum.org/specs/spec_list/

NFC e NDEF summary

NDEF è un formato di encapsulamento dei dati

NFC è una tecnologia wireless a corto raggio che

consente di creare una comunicazione bidirezionale

NFC Technology summary

• NFCoWireless a corto raggio (< 10cm)oFrequenza : 13,56MHz oVelocità di trasmissione massima : 424 Kbit/s.o  E' una evoluzione di RFID

• NDEFo Incapsulamento dei messaggioNFC Forum Device <=> NFC Forum Device oNFC Forum Device <=> NFC Forum TagoMessage = n * RecordsoRecords = Type + Size + Payload (binary data)oTypes: URI, MIME o NFC-specific types

Android

Android

Android Application

Android Application

AndroidManifest.xml

Intents

Activities Services

Broadcast receivers Content providers

AndroidManifest.xml

• Lʼapplicazione deve dichiarare tutti i suoi componenti in questo file.

• Permessi, API level, caratteristiche hardware o software usate, altre libererie API.

<?xml version="1.0" encoding="utf-8"?><manifest ... >    <application android:icon="@drawable/app_icon.png" ... >        <activity android:name="com.example.project.ExampleActivity"                  android:label="@string/example_label" ... >        </activity>        ...    </application></manifest>

Activities

• Ogni Activity rappresenta un unico schermo con una interfaccia utente.

• Ognuna è indipendente dalle altre.• UnʼActivity deve definire come main.• Ogni Activity puo far partire unʼaltra Activity.• Quando parte una nuova Activity quella precedente

si ferma e si conserva dentro uno Stack.• Per creare un Activity dobbiamo estendere classe

astratto Activity e suoi metodi.

Activities

Intents

• Componenti di una applicazione (Activities, Services e Broadcast receivers) vengono attivati attraverso messaggi, chiamate Intents.

Component name

Action

Data

Category

Extra

Flags

Intent

Intent Filters

• Explicit vs Implicit• Per definire quali Intents (impiciti) deve accettare

un componente.

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Summary

• AndroidManifest.xml definice tutti i componenti dellʼapplicazione.

• Ogni schermata dellʼapplicazione è unʼActivity.• Intents sono i messaggi che avviano i componenti.• Usando Intents Filters si possono filtrare Intents

non desiderati.• Se ci sono operazioni lunghe che non richiedono

interfaccia utente si possono usare i Services.

NFC e Android

NFC e Android summary

• Dichiarazione permessi, Intents e Intent filters in Manifest• Dispatch systems

o Intent Dispatch SystemoForeground Dispatch System

• Codice: lettura di un tag NDEF• Codice: scrittura di un tag NDEF• Codice: Foreground dispatch system• Codice: Device to Device (Beam)

AndroidManifest

• Dichiarazione Activities• Dichiarazione Intents• Dichiarazione Intent filters• Permessi• API level • Caratteristiche hardware

Discover NDEF Tag - Intent filter

...<activity>  ...  <intent-filter>

    <action         android:name="android.nfc.action.NDEF_DISCOVERED"/>    <category         android:name="android.intent.category.DEFAULT"/>    <data         android:mimeType="text/plain" />

  </intent-filter>  ...</activity>...

AndroidManifest.xml

Discover NDEF Tag - Permessi

...<uses-permission        android:name="android.permission.NFC" />

<uses-sdk         android:minSdkVersion="10"/>

<uses-feature         android:name="android.hardware.nfc"         android:required="true" />...

AndroidManifest.xml

NFC e Android - dispatch system• Maggior parte delle APIs sono basate su NDEF• The tag dispatch system

NFC e Android - dispatch system• Maggior parte delle APIs sono basate su NDEF• The tag dispatch system

Intent e Foreground Dispatch Systems

Intent Dispatch System• dichiara i filtri nel Manifest• fa partire l'applicazione anche se è spenta

Foreground Dispatch System• dichiara i filtri mentre in esecuzione• gestione esclusiva per i tag richiesti

NDEF Tag - Reading

public class MyNFCActivity extends Activity { 

  @Override   public void onNewIntent(Intent intent) { 

    Parcelable[] raw = intent.getParcelableArrayExtra(                NfcAdapter.EXTRA_NDEF_MESSAGES);

    NdefMessage message = (NdefMessage) raw[0];     NdefRecord record = message.getRecords()[0];     byte[] payload = record.getPayload();     ...

  }

}

1

2

NDEF Tag - Reading

Parcelable[] raw = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

• Prendiamo il tag toccato dallʼIntent ricevuto.

1

NDEF Tag - Reading

NdefMessage message = (NdefMessage) raw[0]; NdefRecord record = message.getRecords()[0]; byte[] payload = record.getPayload();

• Prendiamo il primo record del primo messaggio.• Leggiamo il payload del record.

2

NDEF Tag - Writing

public class MyNFCActivity extends Activity {

  @Override  public void onNewIntent(Intent intent) {    Tag t = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);    Ndef ndef = Ndef.get( t );    ndef.connect();    final byte[] data = …;    NdefRecord record = new NdefRecord(            NdefRecord.TNF_MIME_MEDIA,            "text/plain".getBytes(),            new byte[0],            data);    NdefRecord[] records = new NdefRecord[]{record};    NdefMessage message = new NdefMessage( records );        ndef.writeNdefMessage(message);  }}

1

2

3

NDEF Tag - Writing

Tag t = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

Ndef ndef = Ndef.get( t );ndef.connect();    

• Prendiamo il tag toccato dallʼIntent ricevuto. • Creiamo una istanza Ndef usando quel tag.

1

NDEF Tag - Writing

final byte[] data = …;NdefRecord record = new NdefRecord(

NdefRecord.TNF_MIME_MEDIA,"text/plain".getBytes(),new byte[0],data);

• Creiamo un record Ndef inserendo i nostri dati come MIME type text/plain.

2

NDEF Tag - Writing

NdefRecord[] records = new NdefRecord[]{record};

NdefMessage message = new NdefMessage( records );    

ndef.writeNdefMessage(message);

• Incapsuliamo il record appena creato dentro un messaggio Ndef.

• Scriviamo il nostro messaggio sul tag usando lʼinstanza di Ndef che abbiamo creato prima.

3

Foreground dispatchpublic class MyNFCActivity extends Activity {

@Overridepublic void onCreate(Bundle savedInstanceState){

Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);try {

ndef.addDataType("*/*");} catch (MalformedMimeTypeException e) {

throw new RuntimeException("fail", e);}intentFiltersArray = new IntentFilter[] {ndef};techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

}

@Overridepublic void onPause() {

super.onPause();mAdapter.disableForegroundDispatch(this);

}

@Overridepublic void onResume() {

super.onResume();mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);

}

@Overridepublic void onNewIntent(Intent intent) {

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//do something with tagFromIntent

}}

Foreground dispatchpublic class MyNFCActivity extends Activity {

@Overridepublic void onCreate(Bundle savedInstanceState){

Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);try {

ndef.addDataType("*/*");} catch (MalformedMimeTypeException e) {

throw new RuntimeException("fail", e);}intentFiltersArray = new IntentFilter[] {ndef};techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

}

@Overridepublic void onPause() {

super.onPause();mAdapter.disableForegroundDispatch(this);

}

@Overridepublic void onResume() {

super.onResume();mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);

}

@Overridepublic void onNewIntent(Intent intent) {

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//do something with tagFromIntent

}}

Foreground dispatchpublic void onCreate(Bundle savedInstanceState){ Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0); IntentFilter ndef =

new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

try {ndef.addDataType("*/*");

} catch (MalformedMimeTypeException e) {throw new RuntimeException("fail", e);

}

intentFiltersArray = new IntentFilter[] {ndef};techListsArray =

new String[][] { new String[] { NfcF.class.getName() } };}

1

2

3

Foreground dispatch

Intent i = new Intent(this, getClass());i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

• Usando questo sistema popola i dati del tag quando viene scansionato.

1

Foreground dispatch

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

try {ndef.addDataType("*/*");

} catch (MalformedMimeTypeException e) {throw new RuntimeException("fail", e);

}

• Filtro che accetta tutti i Mime types.

2

Foreground dispatch

intentFiltersArray = new IntentFilter[] {ndef};

techListsArray = new String[][] { new String[] { Ndef.class.getName()

} };

• Teniamo i filtri salvati in una variabile globale per usarli quando abilitiamo dispatch system.

• Impostiamo anche unʼarray con le technologie tag che lʼapplicazione vuole gestire.

3

Foreground dispatchpublic class MyNFCActivity extends Activity {

@Overridepublic void onCreate(Bundle savedInstanceState){

Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);try {

ndef.addDataType("*/*");} catch (MalformedMimeTypeException e) {

throw new RuntimeException("fail", e);}intentFiltersArray = new IntentFilter[] {ndef};techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

}

@Overridepublic void onPause() {

super.onPause();mAdapter.disableForegroundDispatch(this);

}

@Overridepublic void onResume() {

super.onResume();mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);

}

@Overridepublic void onNewIntent(Intent intent) {

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//do something with tagFromIntent

}}

1

2

3

Foreground dispatchpublic class MyNFCActivity extends Activity {

@Overridepublic void onCreate(Bundle savedInstanceState){

Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);try {

ndef.addDataType("*/*");} catch (MalformedMimeTypeException e) {

throw new RuntimeException("fail", e);}intentFiltersArray = new IntentFilter[] {ndef};techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

}

@Overridepublic void onPause() {

super.onPause();mAdapter.disableForegroundDispatch(this);

}

@Overridepublic void onResume() {

super.onResume();mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);

}

@Overridepublic void onNewIntent(Intent intent) {

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//do something with tagFromIntent

}}

1

2

3

Foreground dispatch

@Overridepublic void onResume() {super.onResume();NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);

}

• Abilitiamo foreground dispatch system quando lʼActivity prende il controllo.

1

Foreground dispatch

@Overridepublic void onPause() {super.onPause();NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);

}

• Disabilitiamo foreground dispatch system quando lʼActivity perde il controllo.

2

Foreground dispatch

@Overridepublic void onNewIntent(Intent intent) {Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

//do something with tagFromIntent}

• Riceviamo lʼIntent allo stesso modo di intent dispatch system.

3

Device to Device

• Scambiare dati tra due device Android.• Entrambi i dispositivi deve avere lʼActivity in

foreground e schermo sbloccato.• Un messaggio NDEF alla volta.• Basta utilizzare uno dei metodi

– setNdefPushMessage() – setNdefPushMessageCallback()

Device to Device

public class MyNFCActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {NdefMessage msg = new NdefMessage(...);mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

mNfcAdapter.setNdefPushMessage(msg, this);}

}

setNdefPushMessage()

Device to Device

public class MyNFCActivity extends Activity implements CreateNdefMessageCallback {

@Overridepublic void onCreate(Bundle savedInstanceState) {

mNfcAdapter = NfcAdapter.getDefaultAdapter(this);mNfcAdapter.setNdefPushMessageCallback(this, this);

}

@Overridepublic NdefMessage createNdefMessage(NfcEvent event) {

NdefMessage msg = new NdefMessage(...);return msg;

}}

setNdefPushMessageCallback()

1

2

Device to Device

@Overridepublic void onCreate(Bundle savedInstanceState) {mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

mNfcAdapter.setNdefPushMessageCallback(this, this);

}

Abilitiamo Beam usando il metodo setNdefPushMessageCallback passando come parametri lʼActivity ed una implementazione di NfcAdapter.CreateNdefMessageCallback.

1

Device to Device

@Overridepublic NdefMessage createNdefMessage(NfcEvent event) {NdefMessage msg = new NdefMessage(...);return msg;

}

Creiamo un messaggio da spedire quando avvicina un device e parte la comunicazione.

2

NFC e Android summary

• Dichiarazione permessi, Intents e Intent filters in Manifest• Dispatch systems

o Intent Dispatch SystemoForeground Dispatch System

• Codice: lettura di un tag NDEF• Codice: scrittura di un tag NDEF• Codice: Foreground dispatch system• Codice: Device to Device (Beam)

Safe at work

Safeatwork

Sicurezza sul lavoro e supporto alla certificazione

Usato dai manutentori e operai specializzatiBackend web per la gestione dei dati

Nata su j2me nel 2008( Nokia 6212 )

www.safeatwork.it

Safeatwork

Download contenuti • Schede tecniche• Istruzioni operative

Accesso ai contenuti basato su NFC

Upload delle attività• cosa ha fatto l'operatore?• che procedure ha eseguito?

Safeatwork

Download contenuti • Schede tecniche• Istruzioni operative

Accesso ai contenuti basato su NFC

Upload delle attività• cosa ha fatto l'operatore?• che procedure ha eseguito?

SafeatworkL'interazione prevede prevalentemente l'utilizzo della lettura dei tag per accedere ai contenuti.

SafeatworkL'interazione prevede prevalentemente l'utilizzo della lettura dei tag per accedere ai contenuti.

Safeatwork in action

Safeatwork in action

Grazie

Android NFC developer documentationhttp://developer.android.com/guide/topics/nfc/

Nfc Forumhttp://www.nfc-forum.org/home/

Mytiwww.myti.it

Ishan Fernando@ifdoi.fernando@myti.it