SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
Présentation du NFC
    PA U G S E P T E M B R E 2 0 1 1
Présentation


•   Olivier GONTHIER
    o Etudiant 5A à l'ESIEA
    o Développeur chez SMS-BACKING
    o Portfolio : r0ly.fr
    o Twitter : @rolios



    A la recherche d'un stage de fin d'études…
Plan

• Etat de l’art
• NFC sur Android
  1)   Présentation API
  2)   Permissions requises
  3)   "Foreground dispatch system"
  4)   "Intent dispatch system"
          NDEF discovered
          Tech discovered
          Tag discovered
  5)       Data
          Lecture
          Ecriture
          Peer to peer
• Conclusion
Etat de l'art
Etat de l'art

•   Sur Android, une dizaine d'appareils (Nexus S, Galaxy S II,
    Xperia Acro, Lg LU6200, Acer Liquid express, Sony Nozomi,
    Nexus Prime, LG Gelato nfc, ...)

•   Les prochains blackberry

•   Iphone 5 ?

•   Nokia N9 sous meego

•   Nokia-6131 ( le premier téléphone nfc) , nokia C7

•   Windows phone 7: peu probable pour le moment
1 - Présentation API
    LE NFC SUR ANDROID
Présentation API

•   Introduit avec Android 2.3 et le Nexus S
•   Première API nfc avec Android 2.3 (API 9, Décembre 2010)
         Très limitée
•   API complète avec Android 2.3.3 (API 10, Février 2011)
•   Fournit des outils pour détecter les Tags, lire ou écrire le
    contenu de ces tags, et communiquer avec d'autres puces
    NFC
2 - Permissions requises
      LE NFC SUR ANDROID
Permissions requises

• Pour utiliser le nfc:

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




• Pour n'apparaître sur l'android market que pour les devices

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




• Pour définir le niveau d'api nécessaire:

  <uses-sdk android:minSdkVersion="10"/>
3 - Foreground dispatch system
          LE NFC SUR ANDROID
Foreground dispatch system

Permet de déclarer l’application active comme prioritaire pour le traitement des tags

     pi =
PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTI
VITY_SINGLE_TOP) , 0);

     ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

     try{
     ndef.addDataType("text/plain");
     }catch (MalformedMimeTypeException e) {
        Log.e("NfcForecast", e.getMessage());
     }

     intentFiltersArray = new IntentFilter[] {ndef};

     techList = new String[][]{new String[] {NfcA.class.getName() }};
Foreground dispatch system

@Override
protected void onResume() {
     super.onResume();
     adapter.enableForegroundDispatch(this, pi, intentFiltersArray, techList);
}

@Override
protected void onPause() {
     super.onPause();
     adapter.disableForegroundDispatch(this);
     //ne pas oublier de désactiver quand l’application est suspendue
}

@Override
protected void onNewIntent(Intent intent) {
     super.onNewIntent(intent);
     //Reaction
}
4 - Intent dispatch system
       LE NFC SUR ANDROID
Ndef discovered
     LE NFC SUR ANDROID
4 - I N T E N T D I S PAT C H S Y S T E M
NdefDiscovered

• Pour du texte, ou autre type mime :

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

• Pour une URL :

<intent-filter >
         <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
         <data android:scheme="http" android:host="www.r0ly.fr"/>
         <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
Tech discovered
     LE NFC SUR ANDROID
4 - I N T E N T D I S PAT C H S Y S T E M
Présentation des technologies

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.
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.
Tech discovered
• Dans le manifest:

<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>

<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    android:resource="@xml/techlist"/>

• Dans un fichier xml/techlist.xml:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <tech-list>
      <tech>android.nfc.tech.IsoDep</tech>
      <tech>android.nfc.tech.MifareClassic</tech>
   </tech-list>
</resources>
Tag discovered
     LE NFC SUR ANDROID
4 - I N T E N T D I S PAT C H S Y S T E M
Tag discovered

Dans le manifest:

<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
</intent-filter>

Moins fréquent, surtout si d'autres applications nfc sont installées.
5 - Data
LE NFC SUR ANDROID
Récupérer la référence du tag
• Si on utilise le dispatch system:

    @Override
    protected void onResume() {
         super.onResume();
         Intent i = this.getIntent();
         if(i.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
                  Tag tagFromIntent = i.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    }

•   Si on utilise le foreground system:
    @Override
    protected void onNewIntent(Intent i) {
         super.onNewIntent(intent);
         if(i.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
                  Tag tagFromIntent = i.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    }
Lecture
LE NFC SUR ANDROID
      5 - D ATA
Récupérer les NdefMessage

Les tags contiennent un ensemble de NdefMessage qui contiennent les données.

public NdefMessage[] getNdefMessages(Intent intent){
         NdefMessage[] messages=null;
         Parcelable[] rawMsgs =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
         if (rawMsgs != null) {
                  messages = new NdefMessage[rawMsgs.length];
                  for (int i = 0; i < rawMsgs.length; i++) {
                             messages[i] = (NdefMessage) rawMsgs[i]; }
         } else { // Type du tag inconnu
                  byte[] empty = new byte[] {};
                  NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty,
empty, empty);
                  NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                  messages = new NdefMessage[] {msg};
         }
         return messages; }
NdefRecord

Chaque NdefMessage contient un ensemble de NdefRecord.

Chaque NdefRecord est composé de :
        _ un id : byte[] id = record.getId();

        _ un TypeNameFormat : short tnf = record.getTnf();

        _ un type: byte[] type = record.getType();

        _ un payload = byte[] payload = record.getPayload();



Problème: Il faut "décoder" les informations.
Récupérer les NdefRecords

public NdefRecord[][] getNdefRecords(NdefMessage[] msgs) {

        NdefRecord[][] records=null;

        if(msgs!=null){

                 records = new NdefRecord[msgs.length][];

                 for(int i=0; i<msgs.length; i++){

                          records[i]= new NdefRecord[msgs[i].getRecords().length];

                          records[i]= msgs[i].getRecords(); }

        }

        return records;

}
Décodage, byte[ ] to String
new String(byte[]) est déconseillé, car l'encodage peut varier.

Une solution :

String getTextData(byte[] payload) {
         try {
                 String texteCode = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
                 int langageCodeTaille = payload[0] & 0077;
                 return new String(payload, langageCodeTaille + 1, payload.length -
langageCodeTaille - 1, texteCode);
         }
         catch(UnsupportedEncodingException e){
                 Log.e("NfcReaderActivity", e.getMessage());
                 return null;
         }
}
Ecriture
LE NFC SUR ANDROID
      5 - D ATA
Instancier un NdefRecord

NdefRecord createRecord(String message) {

        byte[] langBytes =
Locale.ENGLISH.getLanguage().getBytes(Charset.forName("US-ASCII"));
        byte[] textBytes = message.getBytes(Charset.forName("UTF-8"));
        char status = (char) (langBytes.length);
        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        data[0] = (byte) status;
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
textBytes.length);

       return new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
 }
Ecrire le tag

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        try{
                NdefRecord[] records = {createRecord("Test Message")};
                NdefMessage message = new NdefMessage(records);

                Ndef ndef = Ndef.get(tag);

                ndef.connect();
                ndef.writeNdefMessage(message);
                ndef.close();
       }(...)
Peer to peer
LE NFC SUR ANDROID
      5 - D ATA
Peer to peer

Moyen de communication intéressant : envoie continuellement des NdefMessage.

public void onResume() {
        super.onResume();
        if (mAdapter != null)
        mAdapter.enableForegroundNdefPush(this,myNdefMessage);
  }

public void onPause() {
        super.onPause();
        if (mAdapter != null)
        mAdapter.disableForegroundNdefPush(this);
  }
Conclusion
Conclusion

Points importants à retenir :


• Etre le plus précis possible pour la récupération des tags : définir la
  technologie attendue ainsi que son contenu

• Pour la lecture, faire attention au décodage

• Pour l’écriture, bien construire son NdefRecord
Merci de votre attention!

Más contenido relacionado

La actualidad más candente

API Cockpit : faites communiquer vos applications web
API Cockpit : faites communiquer vos applications webAPI Cockpit : faites communiquer vos applications web
API Cockpit : faites communiquer vos applications webParis, France
 
AKT un outil pour sécuriser vos données et documents sensibles
AKT un outil pour sécuriser vos données et documents sensiblesAKT un outil pour sécuriser vos données et documents sensibles
AKT un outil pour sécuriser vos données et documents sensiblesStephane Carrez
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancépierrepo
 
Trouvez la faille! - Confoo 2012
Trouvez la faille! - Confoo 2012Trouvez la faille! - Confoo 2012
Trouvez la faille! - Confoo 2012Antonio Fontes
 
Python For Data Science - French Course
Python For Data Science - French CoursePython For Data Science - French Course
Python For Data Science - French CourseHaytam EL YOUSSFI
 
Initiation à l'algorithmique
Initiation à l'algorithmiqueInitiation à l'algorithmique
Initiation à l'algorithmiqueAbdoulaye Dieng
 
How with Suricata you save the world - NDH2K14
How with Suricata you save the world - NDH2K14How with Suricata you save the world - NDH2K14
How with Suricata you save the world - NDH2K14Sebastien Larinier
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresECAM Brussels Engineering School
 
Développement informatique : Algorithmique I : Récursion et arbre
Développement informatique : Algorithmique I : Récursion et arbreDéveloppement informatique : Algorithmique I : Récursion et arbre
Développement informatique : Algorithmique I : Récursion et arbreECAM Brussels Engineering School
 
Python avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionPython avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionECAM Brussels Engineering School
 
Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScriptAbdoulaye Dieng
 
Développement informatique : Gestion de projet, versioning, debugging, testin...
Développement informatique : Gestion de projet, versioning, debugging, testin...Développement informatique : Gestion de projet, versioning, debugging, testin...
Développement informatique : Gestion de projet, versioning, debugging, testin...ECAM Brussels Engineering School
 

La actualidad más candente (17)

Introduction à jQuery
Introduction à jQueryIntroduction à jQuery
Introduction à jQuery
 
API Cockpit : faites communiquer vos applications web
API Cockpit : faites communiquer vos applications webAPI Cockpit : faites communiquer vos applications web
API Cockpit : faites communiquer vos applications web
 
AKT un outil pour sécuriser vos données et documents sensibles
AKT un outil pour sécuriser vos données et documents sensiblesAKT un outil pour sécuriser vos données et documents sensibles
AKT un outil pour sécuriser vos données et documents sensibles
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancé
 
Introduction au Jquery
Introduction au JqueryIntroduction au Jquery
Introduction au Jquery
 
Trouvez la faille! - Confoo 2012
Trouvez la faille! - Confoo 2012Trouvez la faille! - Confoo 2012
Trouvez la faille! - Confoo 2012
 
Python avancé : Qualité de code et convention de codage
Python avancé : Qualité de code et convention de codagePython avancé : Qualité de code et convention de codage
Python avancé : Qualité de code et convention de codage
 
Développement informatique : Programmation concurrente
Développement informatique : Programmation concurrenteDéveloppement informatique : Programmation concurrente
Développement informatique : Programmation concurrente
 
Python For Data Science - French Course
Python For Data Science - French CoursePython For Data Science - French Course
Python For Data Science - French Course
 
Initiation à l'algorithmique
Initiation à l'algorithmiqueInitiation à l'algorithmique
Initiation à l'algorithmique
 
How with Suricata you save the world - NDH2K14
How with Suricata you save the world - NDH2K14How with Suricata you save the world - NDH2K14
How with Suricata you save the world - NDH2K14
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulières
 
Développement informatique : Algorithmique I : Récursion et arbre
Développement informatique : Algorithmique I : Récursion et arbreDéveloppement informatique : Algorithmique I : Récursion et arbre
Développement informatique : Algorithmique I : Récursion et arbre
 
Python avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exceptionPython avancé : Gestion d'erreurs et mécanisme d'exception
Python avancé : Gestion d'erreurs et mécanisme d'exception
 
Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScript
 
Johnny-Five : Robotique et IoT en JavaScript
Johnny-Five : Robotique et IoT en JavaScriptJohnny-Five : Robotique et IoT en JavaScript
Johnny-Five : Robotique et IoT en JavaScript
 
Développement informatique : Gestion de projet, versioning, debugging, testin...
Développement informatique : Gestion de projet, versioning, debugging, testin...Développement informatique : Gestion de projet, versioning, debugging, testin...
Développement informatique : Gestion de projet, versioning, debugging, testin...
 

Similar a Code Demo NFC on Android - Olivier Gonthier - PAUG

Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++cppfrug
 
Partie1 TypeScript
Partie1 TypeScriptPartie1 TypeScript
Partie1 TypeScriptHabib Ayad
 
gRPC, échange à haute fréquence!
gRPC, échange à haute fréquence!gRPC, échange à haute fréquence!
gRPC, échange à haute fréquence!David Caramelo
 
gRPC, ECHANGES A HAUTE FREQUENCE !
gRPC, ECHANGES A HAUTE FREQUENCE !gRPC, ECHANGES A HAUTE FREQUENCE !
gRPC, ECHANGES A HAUTE FREQUENCE !Carles Sistare
 
php2 : formulaire-session-PDO
php2 : formulaire-session-PDOphp2 : formulaire-session-PDO
php2 : formulaire-session-PDOAbdoulaye Dieng
 
201303 - Java8
201303 - Java8201303 - Java8
201303 - Java8lyonjug
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à AndroidYoann Gotthilf
 
Architecture hétérogène au service de l'IoT industriel ?
Architecture hétérogène au service de l'IoT industriel ?Architecture hétérogène au service de l'IoT industriel ?
Architecture hétérogène au service de l'IoT industriel ?Pierre-jean Texier
 
Entity framework core 2 vs micro orm performances
Entity framework core 2 vs micro orm performancesEntity framework core 2 vs micro orm performances
Entity framework core 2 vs micro orm performancesMSDEVMTL
 
Utiliser le Zend Framework avec Symfony
Utiliser le Zend Framework avec SymfonyUtiliser le Zend Framework avec Symfony
Utiliser le Zend Framework avec SymfonyXavier Gorse
 
Réunion technique Android
Réunion technique AndroidRéunion technique Android
Réunion technique Androidnaholyr
 
Dotnet csharp
Dotnet csharpDotnet csharp
Dotnet csharpSDFG5
 

Similar a Code Demo NFC on Android - Olivier Gonthier - PAUG (20)

Apple : iOS
Apple : iOSApple : iOS
Apple : iOS
 
Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++
 
Partie1 TypeScript
Partie1 TypeScriptPartie1 TypeScript
Partie1 TypeScript
 
gRPC, échange à haute fréquence!
gRPC, échange à haute fréquence!gRPC, échange à haute fréquence!
gRPC, échange à haute fréquence!
 
gRPC, ECHANGES A HAUTE FREQUENCE !
gRPC, ECHANGES A HAUTE FREQUENCE !gRPC, ECHANGES A HAUTE FREQUENCE !
gRPC, ECHANGES A HAUTE FREQUENCE !
 
php2 : formulaire-session-PDO
php2 : formulaire-session-PDOphp2 : formulaire-session-PDO
php2 : formulaire-session-PDO
 
Paug renderscript-mars-2013
Paug renderscript-mars-2013Paug renderscript-mars-2013
Paug renderscript-mars-2013
 
201303 - Java8
201303 - Java8201303 - Java8
201303 - Java8
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à Android
 
IoT.pptx
IoT.pptxIoT.pptx
IoT.pptx
 
Norme NFC - Romain Menetrier PAUG
Norme NFC - Romain Menetrier PAUGNorme NFC - Romain Menetrier PAUG
Norme NFC - Romain Menetrier PAUG
 
Architecture hétérogène au service de l'IoT industriel ?
Architecture hétérogène au service de l'IoT industriel ?Architecture hétérogène au service de l'IoT industriel ?
Architecture hétérogène au service de l'IoT industriel ?
 
Configuration rnis
Configuration rnisConfiguration rnis
Configuration rnis
 
Support NodeJS avec TypeScript Express MongoDB
Support NodeJS avec TypeScript Express MongoDBSupport NodeJS avec TypeScript Express MongoDB
Support NodeJS avec TypeScript Express MongoDB
 
OWF12/PHP de inetd à ZeroMQ
OWF12/PHP de inetd à ZeroMQOWF12/PHP de inetd à ZeroMQ
OWF12/PHP de inetd à ZeroMQ
 
Entity framework core 2 vs micro orm performances
Entity framework core 2 vs micro orm performancesEntity framework core 2 vs micro orm performances
Entity framework core 2 vs micro orm performances
 
Aspectj
AspectjAspectj
Aspectj
 
Utiliser le Zend Framework avec Symfony
Utiliser le Zend Framework avec SymfonyUtiliser le Zend Framework avec Symfony
Utiliser le Zend Framework avec Symfony
 
Réunion technique Android
Réunion technique AndroidRéunion technique Android
Réunion technique Android
 
Dotnet csharp
Dotnet csharpDotnet csharp
Dotnet csharp
 

Más de Paris Android User Group

Workshop: building your mobile backend with Parse - Droidcon Paris2014
Workshop: building your mobile backend with Parse - Droidcon Paris2014Workshop: building your mobile backend with Parse - Droidcon Paris2014
Workshop: building your mobile backend with Parse - Droidcon Paris2014Paris Android User Group
 
Workshop: Amazon developer ecosystem - DroidCon Paris2014
Workshop: Amazon developer ecosystem - DroidCon Paris2014Workshop: Amazon developer ecosystem - DroidCon Paris2014
Workshop: Amazon developer ecosystem - DroidCon Paris2014Paris Android User Group
 
Extending your apps to wearables - DroidCon Paris 2014
Extending your apps to wearables -  DroidCon Paris 2014Extending your apps to wearables -  DroidCon Paris 2014
Extending your apps to wearables - DroidCon Paris 2014Paris Android User Group
 
Scaling android development - DroidCon Paris 2014
Scaling android development - DroidCon Paris 2014Scaling android development - DroidCon Paris 2014
Scaling android development - DroidCon Paris 2014Paris Android User Group
 
Ingredient of awesome app - DroidCon Paris 2014
Ingredient of awesome app - DroidCon Paris 2014Ingredient of awesome app - DroidCon Paris 2014
Ingredient of awesome app - DroidCon Paris 2014Paris Android User Group
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Paris Android User Group
 
Archos Android based connected home solution - DroidCon Paris 2014
Archos Android based connected home solution - DroidCon Paris 2014Archos Android based connected home solution - DroidCon Paris 2014
Archos Android based connected home solution - DroidCon Paris 2014Paris Android User Group
 
Porting VLC on Android - DroidCon Paris 2014
Porting VLC on Android - DroidCon Paris 2014Porting VLC on Android - DroidCon Paris 2014
Porting VLC on Android - DroidCon Paris 2014Paris Android User Group
 
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014Paris Android User Group
 
maximize app engagement and monetization - DroidCon Paris 2014
maximize app engagement and monetization - DroidCon Paris 2014maximize app engagement and monetization - DroidCon Paris 2014
maximize app engagement and monetization - DroidCon Paris 2014Paris Android User Group
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Paris Android User Group
 
Holo material design transition - DroidCon Paris 2014
Holo material design transition - DroidCon Paris 2014Holo material design transition - DroidCon Paris 2014
Holo material design transition - DroidCon Paris 2014Paris Android User Group
 
Google glass droidcon - DroidCon Paris 2014
Google glass droidcon - DroidCon Paris 2014Google glass droidcon - DroidCon Paris 2014
Google glass droidcon - DroidCon Paris 2014Paris Android User Group
 
Embedded webserver implementation and usage - DroidCon Paris 2014
Embedded webserver implementation and usage - DroidCon Paris 2014Embedded webserver implementation and usage - DroidCon Paris 2014
Embedded webserver implementation and usage - DroidCon Paris 2014Paris Android User Group
 
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014Paris Android User Group
 
What's new in android 4.4 - Romain Guy & Chet Haase
What's new in android 4.4 - Romain Guy & Chet HaaseWhat's new in android 4.4 - Romain Guy & Chet Haase
What's new in android 4.4 - Romain Guy & Chet HaaseParis Android User Group
 
Efficient Image Processing - Nicolas Roard
Efficient Image Processing - Nicolas RoardEfficient Image Processing - Nicolas Roard
Efficient Image Processing - Nicolas RoardParis Android User Group
 

Más de Paris Android User Group (20)

Workshop: building your mobile backend with Parse - Droidcon Paris2014
Workshop: building your mobile backend with Parse - Droidcon Paris2014Workshop: building your mobile backend with Parse - Droidcon Paris2014
Workshop: building your mobile backend with Parse - Droidcon Paris2014
 
Workshop: Amazon developer ecosystem - DroidCon Paris2014
Workshop: Amazon developer ecosystem - DroidCon Paris2014Workshop: Amazon developer ecosystem - DroidCon Paris2014
Workshop: Amazon developer ecosystem - DroidCon Paris2014
 
Extending your apps to wearables - DroidCon Paris 2014
Extending your apps to wearables -  DroidCon Paris 2014Extending your apps to wearables -  DroidCon Paris 2014
Extending your apps to wearables - DroidCon Paris 2014
 
Scaling android development - DroidCon Paris 2014
Scaling android development - DroidCon Paris 2014Scaling android development - DroidCon Paris 2014
Scaling android development - DroidCon Paris 2014
 
Ingredient of awesome app - DroidCon Paris 2014
Ingredient of awesome app - DroidCon Paris 2014Ingredient of awesome app - DroidCon Paris 2014
Ingredient of awesome app - DroidCon Paris 2014
 
Framing the canvas - DroidCon Paris 2014
Framing the canvas - DroidCon Paris 2014Framing the canvas - DroidCon Paris 2014
Framing the canvas - DroidCon Paris 2014
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014
 
Archos Android based connected home solution - DroidCon Paris 2014
Archos Android based connected home solution - DroidCon Paris 2014Archos Android based connected home solution - DroidCon Paris 2014
Archos Android based connected home solution - DroidCon Paris 2014
 
Porting VLC on Android - DroidCon Paris 2014
Porting VLC on Android - DroidCon Paris 2014Porting VLC on Android - DroidCon Paris 2014
Porting VLC on Android - DroidCon Paris 2014
 
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
Robotium vs Espresso: Get ready to rumble ! - DroidCon Paris 2014
 
Buildsystem.mk - DroidCon Paris 2014
Buildsystem.mk - DroidCon Paris 2014Buildsystem.mk - DroidCon Paris 2014
Buildsystem.mk - DroidCon Paris 2014
 
maximize app engagement and monetization - DroidCon Paris 2014
maximize app engagement and monetization - DroidCon Paris 2014maximize app engagement and monetization - DroidCon Paris 2014
maximize app engagement and monetization - DroidCon Paris 2014
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
 
Holo material design transition - DroidCon Paris 2014
Holo material design transition - DroidCon Paris 2014Holo material design transition - DroidCon Paris 2014
Holo material design transition - DroidCon Paris 2014
 
Death to passwords - DroidCon Paris 2014
Death to passwords - DroidCon Paris 2014Death to passwords - DroidCon Paris 2014
Death to passwords - DroidCon Paris 2014
 
Google glass droidcon - DroidCon Paris 2014
Google glass droidcon - DroidCon Paris 2014Google glass droidcon - DroidCon Paris 2014
Google glass droidcon - DroidCon Paris 2014
 
Embedded webserver implementation and usage - DroidCon Paris 2014
Embedded webserver implementation and usage - DroidCon Paris 2014Embedded webserver implementation and usage - DroidCon Paris 2014
Embedded webserver implementation and usage - DroidCon Paris 2014
 
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
Petit design Grande humanité par Geoffrey Dorne - DroidCon Paris 2014
 
What's new in android 4.4 - Romain Guy & Chet Haase
What's new in android 4.4 - Romain Guy & Chet HaaseWhat's new in android 4.4 - Romain Guy & Chet Haase
What's new in android 4.4 - Romain Guy & Chet Haase
 
Efficient Image Processing - Nicolas Roard
Efficient Image Processing - Nicolas RoardEfficient Image Processing - Nicolas Roard
Efficient Image Processing - Nicolas Roard
 

Code Demo NFC on Android - Olivier Gonthier - PAUG

  • 1. Présentation du NFC PA U G S E P T E M B R E 2 0 1 1
  • 2. Présentation • Olivier GONTHIER o Etudiant 5A à l'ESIEA o Développeur chez SMS-BACKING o Portfolio : r0ly.fr o Twitter : @rolios A la recherche d'un stage de fin d'études…
  • 3. Plan • Etat de l’art • NFC sur Android 1) Présentation API 2) Permissions requises 3) "Foreground dispatch system" 4) "Intent dispatch system"  NDEF discovered  Tech discovered  Tag discovered 5) Data  Lecture  Ecriture  Peer to peer • Conclusion
  • 5. Etat de l'art • Sur Android, une dizaine d'appareils (Nexus S, Galaxy S II, Xperia Acro, Lg LU6200, Acer Liquid express, Sony Nozomi, Nexus Prime, LG Gelato nfc, ...) • Les prochains blackberry • Iphone 5 ? • Nokia N9 sous meego • Nokia-6131 ( le premier téléphone nfc) , nokia C7 • Windows phone 7: peu probable pour le moment
  • 6. 1 - Présentation API LE NFC SUR ANDROID
  • 7. Présentation API • Introduit avec Android 2.3 et le Nexus S • Première API nfc avec Android 2.3 (API 9, Décembre 2010)  Très limitée • API complète avec Android 2.3.3 (API 10, Février 2011) • Fournit des outils pour détecter les Tags, lire ou écrire le contenu de ces tags, et communiquer avec d'autres puces NFC
  • 8. 2 - Permissions requises LE NFC SUR ANDROID
  • 9. Permissions requises • Pour utiliser le nfc: <uses-permission android:name="android.permission.NFC" /> • Pour n'apparaître sur l'android market que pour les devices ayant une puce nfc: <uses-feature android:name="android.hardware.nfc" android:required="true" /> • Pour définir le niveau d'api nécessaire: <uses-sdk android:minSdkVersion="10"/>
  • 10. 3 - Foreground dispatch system LE NFC SUR ANDROID
  • 11. Foreground dispatch system Permet de déclarer l’application active comme prioritaire pour le traitement des tags pi = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTI VITY_SINGLE_TOP) , 0); ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try{ ndef.addDataType("text/plain"); }catch (MalformedMimeTypeException e) { Log.e("NfcForecast", e.getMessage()); } intentFiltersArray = new IntentFilter[] {ndef}; techList = new String[][]{new String[] {NfcA.class.getName() }};
  • 12. Foreground dispatch system @Override protected void onResume() { super.onResume(); adapter.enableForegroundDispatch(this, pi, intentFiltersArray, techList); } @Override protected void onPause() { super.onPause(); adapter.disableForegroundDispatch(this); //ne pas oublier de désactiver quand l’application est suspendue } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Reaction }
  • 13. 4 - Intent dispatch system LE NFC SUR ANDROID
  • 14. Ndef discovered LE NFC SUR ANDROID 4 - I N T E N T D I S PAT C H S Y S T E M
  • 15. NdefDiscovered • Pour du texte, ou autre type mime : <intent-filter > <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <data android:mimeType="text/plain"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> • Pour une URL : <intent-filter > <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <data android:scheme="http" android:host="www.r0ly.fr"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter>
  • 16. Tech discovered LE NFC SUR ANDROID 4 - I N T E N T D I S PAT C H S Y S T E M
  • 17. Présentation des technologies 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. 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.
  • 18. Tech discovered • Dans le manifest: <intent-filter> <action android:name="android.nfc.action.TECH_DISCOVERED"/> </intent-filter> <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/techlist"/> • Dans un fichier xml/techlist.xml: <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <tech-list> <tech>android.nfc.tech.IsoDep</tech> <tech>android.nfc.tech.MifareClassic</tech> </tech-list> </resources>
  • 19. Tag discovered LE NFC SUR ANDROID 4 - I N T E N T D I S PAT C H S Y S T E M
  • 20. Tag discovered Dans le manifest: <intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED"/> </intent-filter> Moins fréquent, surtout si d'autres applications nfc sont installées.
  • 21. 5 - Data LE NFC SUR ANDROID
  • 22. Récupérer la référence du tag • Si on utilise le dispatch system: @Override protected void onResume() { super.onResume(); Intent i = this.getIntent(); if(i.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) Tag tagFromIntent = i.getParcelableExtra(NfcAdapter.EXTRA_TAG); } • Si on utilise le foreground system: @Override protected void onNewIntent(Intent i) { super.onNewIntent(intent); if(i.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) Tag tagFromIntent = i.getParcelableExtra(NfcAdapter.EXTRA_TAG); }
  • 23. Lecture LE NFC SUR ANDROID 5 - D ATA
  • 24. Récupérer les NdefMessage Les tags contiennent un ensemble de NdefMessage qui contiennent les données. public NdefMessage[] getNdefMessages(Intent intent){ NdefMessage[] messages=null; Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { messages = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { messages[i] = (NdefMessage) rawMsgs[i]; } } else { // Type du tag inconnu byte[] empty = new byte[] {}; NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty); NdefMessage msg = new NdefMessage(new NdefRecord[] {record}); messages = new NdefMessage[] {msg}; } return messages; }
  • 25. NdefRecord Chaque NdefMessage contient un ensemble de NdefRecord. Chaque NdefRecord est composé de : _ un id : byte[] id = record.getId(); _ un TypeNameFormat : short tnf = record.getTnf(); _ un type: byte[] type = record.getType(); _ un payload = byte[] payload = record.getPayload(); Problème: Il faut "décoder" les informations.
  • 26. Récupérer les NdefRecords public NdefRecord[][] getNdefRecords(NdefMessage[] msgs) { NdefRecord[][] records=null; if(msgs!=null){ records = new NdefRecord[msgs.length][]; for(int i=0; i<msgs.length; i++){ records[i]= new NdefRecord[msgs[i].getRecords().length]; records[i]= msgs[i].getRecords(); } } return records; }
  • 27. Décodage, byte[ ] to String new String(byte[]) est déconseillé, car l'encodage peut varier. Une solution : String getTextData(byte[] payload) { try { String texteCode = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16"; int langageCodeTaille = payload[0] & 0077; return new String(payload, langageCodeTaille + 1, payload.length - langageCodeTaille - 1, texteCode); } catch(UnsupportedEncodingException e){ Log.e("NfcReaderActivity", e.getMessage()); return null; } }
  • 28. Ecriture LE NFC SUR ANDROID 5 - D ATA
  • 29. Instancier un NdefRecord NdefRecord createRecord(String message) { byte[] langBytes = Locale.ENGLISH.getLanguage().getBytes(Charset.forName("US-ASCII")); byte[] textBytes = message.getBytes(Charset.forName("UTF-8")); char status = (char) (langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); }
  • 30. Ecrire le tag Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try{ NdefRecord[] records = {createRecord("Test Message")}; NdefMessage message = new NdefMessage(records); Ndef ndef = Ndef.get(tag); ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); }(...)
  • 31. Peer to peer LE NFC SUR ANDROID 5 - D ATA
  • 32. Peer to peer Moyen de communication intéressant : envoie continuellement des NdefMessage. public void onResume() { super.onResume(); if (mAdapter != null) mAdapter.enableForegroundNdefPush(this,myNdefMessage); } public void onPause() { super.onPause(); if (mAdapter != null) mAdapter.disableForegroundNdefPush(this); }
  • 34. Conclusion Points importants à retenir : • Etre le plus précis possible pour la récupération des tags : définir la technologie attendue ainsi que son contenu • Pour la lecture, faire attention au décodage • Pour l’écriture, bien construire son NdefRecord
  • 35. Merci de votre attention!