webdebs nfc presentation

67
NFC Programming in Android Ishan Fernando @ifdo [email protected] Myti s.r.l. www.myti.it

Upload: myti-srl

Post on 05-Dec-2014

1.141 views

Category:

Technology


3 download

DESCRIPTION

Presentation about NFC technology and developing Android applications using it.

TRANSCRIPT

Page 1: WEBdeBS NFC Presentation

NFC Programming in Android

Ishan Fernando@ifdo

[email protected]

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

Page 2: WEBdeBS NFC Presentation

NFC

• Comunicazione contactless• Nuova interazione utente • Sicurezza

Page 3: WEBdeBS NFC Presentation

NFC (Near Field Communication)

Page 4: WEBdeBS NFC Presentation

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

Page 5: WEBdeBS NFC Presentation

NFC (Near Field Communication)

E' una evoluzione di RFID (Radio Frequency Identification)

Page 6: WEBdeBS NFC Presentation

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

Page 7: WEBdeBS NFC Presentation

Storia

Page 8: WEBdeBS NFC Presentation

NDEF (NFC Data Exchange Format)

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

Page 9: WEBdeBS NFC Presentation

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

Page 10: WEBdeBS NFC Presentation

NDEF (NFC Data Exchange Format)

Message = n * Records

Records = Type +Size + 

Payload (binary data)

Page 11: WEBdeBS NFC Presentation

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/

Page 12: WEBdeBS NFC Presentation

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

Page 13: WEBdeBS NFC Presentation

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

Page 14: WEBdeBS NFC Presentation

Android

Page 15: WEBdeBS NFC Presentation

Android

Page 16: WEBdeBS NFC Presentation

Android Application

Android Application

AndroidManifest.xml

Intents

Activities Services

Broadcast receivers Content providers

Page 17: WEBdeBS NFC Presentation

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>

Page 18: WEBdeBS NFC Presentation

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.

Page 19: WEBdeBS NFC Presentation

Activities

Page 20: WEBdeBS NFC Presentation

Intents

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

Component name

Action

Data

Category

Extra

Flags

Intent

Page 21: WEBdeBS NFC Presentation

Intent Filters

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

un componente.

Page 22: WEBdeBS NFC Presentation

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Page 23: WEBdeBS NFC Presentation

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Page 24: WEBdeBS NFC Presentation

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Page 25: WEBdeBS NFC Presentation

Services

• Per gestire operazioni lunghe in background senza intefaccia utente.

• Servizi hanno due formi: Started e Bound

Page 26: WEBdeBS NFC Presentation

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.

Page 27: WEBdeBS NFC Presentation

NFC e Android

Page 28: WEBdeBS NFC Presentation

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)

Page 29: WEBdeBS NFC Presentation

AndroidManifest

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

Page 30: WEBdeBS NFC Presentation

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

Page 31: WEBdeBS NFC Presentation

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

Page 32: WEBdeBS NFC Presentation

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

Page 33: WEBdeBS NFC Presentation

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

Page 34: WEBdeBS NFC Presentation

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

Page 35: WEBdeBS NFC Presentation

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

Page 36: WEBdeBS NFC Presentation

NDEF Tag - Reading

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

• Prendiamo il tag toccato dallʼIntent ricevuto.

1

Page 37: WEBdeBS NFC Presentation

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

Page 38: WEBdeBS NFC Presentation

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

Page 39: WEBdeBS NFC Presentation

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

Page 40: WEBdeBS NFC Presentation

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

Page 41: WEBdeBS NFC Presentation

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

Page 42: WEBdeBS NFC Presentation

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

}}

Page 43: WEBdeBS NFC Presentation

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

}}

Page 44: WEBdeBS NFC Presentation

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

Page 45: WEBdeBS NFC Presentation

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

Page 46: WEBdeBS NFC Presentation

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

Page 47: WEBdeBS NFC Presentation

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

Page 48: WEBdeBS NFC Presentation

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

Page 49: WEBdeBS NFC Presentation

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

Page 50: WEBdeBS NFC Presentation

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

Page 51: WEBdeBS NFC Presentation

Foreground dispatch

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

}

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

2

Page 52: WEBdeBS NFC Presentation

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

Page 53: WEBdeBS NFC Presentation

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()

Page 54: WEBdeBS NFC Presentation

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()

Page 55: WEBdeBS NFC Presentation

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

Page 56: WEBdeBS NFC Presentation

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

Page 57: WEBdeBS NFC Presentation

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

Page 58: WEBdeBS NFC Presentation

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)

Page 59: WEBdeBS NFC Presentation

Safe at work

Page 60: WEBdeBS NFC Presentation

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

Page 61: WEBdeBS NFC Presentation

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?

Page 62: WEBdeBS NFC Presentation

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?

Page 63: WEBdeBS NFC Presentation

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

Page 64: WEBdeBS NFC Presentation

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

Page 65: WEBdeBS NFC Presentation

Safeatwork in action

Page 66: WEBdeBS NFC Presentation

Safeatwork in action

Page 67: WEBdeBS NFC Presentation

Grazie

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

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

Mytiwww.myti.it

Ishan [email protected]@myti.it