IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Android Discussion :

Android, NFC et tag vide


Sujet :

API standards et tierces Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Par défaut Android, NFC et tag vide
    Bonjour à tous,
    Je souhaite récupérer l'id d'un tag nfc. Cela marche très bien s'il existe un champ dans le tag, par contre si le tag est vide, l'application n'est pas lancée.

    Je suppose que cela vient de la config dans le AndroidManifest mais je ne vois pas ce qui cloche.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    <activity
                android:name="com.dirix.nfctask.NfcReader"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.nfc.action.TECH_DISCOVERED" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
                <meta-data
                    android:name="android.nfc.action.TECH_DISCOVERED"
                    android:resource="@xml/nfc_tech_filter" />
            </activity>
    nf_tech_filter.xml :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    <?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
            <tech-list>
                <tech>android.nfc.tech.IsoDep</tech>
                <tech>android.nfc.tech.NfcA</tech>
                <tech>android.nfc.tech.NfcB</tech>
                <tech>android.nfc.tech.NfcF</tech>
                <tech>android.nfc.tech.NfcV</tech>
                <tech>android.nfc.tech.Ndef</tech>
                <tech>android.nfc.tech.NdefFormatable</tech>
                <tech>android.nfc.tech.MifareClassic</tech>
                <tech>android.nfc.tech.MifareUltralight</tech>
            </tech-list>
        </resources>
    Merci d'avance pour votre aide!

  2. #2
    Membre très actif
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Par défaut TAG_DISCOVERED
    Peut être en ajoutant ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    <intent-filter>
            <action android:name="android.nfc.action.TAG_DISCOVERED" />
     
            <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    Personellement j'ajoute encore le Ndef afin d'être sûre de récupérer tous les tags. Mais cela dépend des besoins de ton appli.

    Ndef :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
     
            <category android:name="android.intent.category.DEFAULT" />
     
            <data android:mimeType="*/*" />
    </intent-filter>

  3. #3
    Membre émérite
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Par défaut
    Merci pour ta réponse!
    En faisant ça, l'appli se lance bien lors du passage d'un tag mais la méthode onNewIntent n'est pas appelée du coup je ne peux pas récupérer les infos du tag!

  4. #4
    Membre très actif
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Par défaut
    Oui c'est normal, les filtres placé dans le manifest.xml définissent une action qui doit lancer ton application. Ce n'est donc pas onNewIntent() qui sera appelé, mais onCreate(), avec un intent contenant l'action ACTION_TAG_DISCOVERED ou ACTION_TECH_DISCOVERED.

    Voici un exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    @Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		Log.i(TAG, "onCreate, action : " + getIntent().getAction());
     
    		//Launched by tag scan ? 
    		Tag tag = (Tag)getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
    		if(tag != null && (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) 
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))){
    			Log.i(TAG, "onCreate, tag found, calling onNewTag");
    			getNewTag(tag, getIntent());
    		}		
     
     
     
    	}
    onNewIntent n'est appelé que lorsque un tag est scanné et que l'application est déjà exécuteée (affichée à l'écran). De plus il faut définir un "PendingIntent" pour que cela fonctionne. Voici un exemple d'un activité complète utilisant un PendingIntent. C'est une classe activity de base que j'utilise dans mes applications, j'hérite ensuite de cette classe avec toutes les activité de mon application, de cette façon un tag est détecté depuis n'importe quelle activité par défaut. J'ai défini la fonction onNewTag(), qui sera appelé dans les classes enfant dés qu'un nouveau tag est détecté.

    BaseActivity:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    public class NfcBaseActivity extends Activity{
     
    	private final static String TAG = NfcBaseActivity.class.getSimpleName();	
    	private PendingIntent mPendingIntent;
    	private static IntentFilter[] mIntentFiltersArray;
    	private static String[][] mTechListsArray;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {		
    		super.onCreate(savedInstanceState);
    		Log.i(TAG, "onCreate, action : " + getIntent().getAction());
     
    		//Get NFC ADAPTER (if NFC enabled)
    		mAdapter = NfcAdapter.getDefaultAdapter(this);											
    		if (mAdapter == null) {
    			Alert(R.string.nfc_error, R.string.no_nfc);
    		}
    		// Android system will populate it with the details of the tag when it is scanned
    		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
     
    		//Launched by tag scan ? 
    		Tag tag = (Tag)getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
    		if(tag != null && (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) 
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))){			
    			Log.i(TAG, "onCreate, tag found, calling onNewTag");
    			getNewTag(tag, getIntent());
    			//Clear intent
    			setIntent(null);
    		}		
    	}
     
    	//Static initialization
    	static{
     
    		// add intent filter
    		IntentFilter mndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);				
    		IntentFilter mtech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    		IntentFilter mtag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    		try {
    			//Handles all MIME based dispatches !!! specify only the ones that you need.
    			mndef.addDataType("*/*");   															
     
    		}
    		catch (MalformedMimeTypeException e) {
    			throw new RuntimeException("fail", e);
    		}
     
    		mIntentFiltersArray = new IntentFilter[] {mndef,mtech,mtag };
    		//array of TAG TECHNOLOGIES that your application wants to handle 
    		mTechListsArray = new String[][] { new String[] { NfcA.class.getName()},				
    				new String[] {NfcB.class.getName()},
    				new String[] {NfcV.class.getName()}, 
    				new String[] {IsoDep.class.getName()}, 
    				new String[] {Ndef.class.getName()}};
    	}
     
    	private void getNewTag(Tag tag, Intent intent){
    		if(tag == null) return;                              
            //Indicate to childs that a new tag has been detected
    		onNewTag(tag);				
    	}
     
    	@Override 
    	public void onNewIntent(Intent intent){
    		Log.i(TAG, "onNewIntent : " + intent.getAction());
     
            // get the tag object for the discovered tag
    		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    		getNewTag(tag, intent);
    	}
     
    	//This function is called in child activities when a new tag is scanned.
    	public void onNewTag(Tag tag){}
     
    	@Override
    	public void onPause() {
    		super.onPause();	
    		Log.i(TAG, "onPause");
     
            mAdapter.disableForegroundDispatch(this);
    	}
     
    	@Override
    	public void onResume() {																	
    		super.onResume();	
    		Log.i(TAG, "onResume");
            //treats all incoming intents when a tag is scanned and the appli is in foreground    
            mAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFiltersArray, mTechListsArray);
    	}
    }
    Utilisation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    public class MyActivity extends NfcBaseActivity {
        @Override
        public void onNewTag(Tag tag){
            //Cette fonction est appelé dés qu'un tag est scanné
        }
    }
    Bien sûre il n'est pas nécessaire de créer une activité de base et d'en hériter si une seule activité dois gérer la connexion d'un tag.

  5. #5
    Membre émérite
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Par défaut
    Super merci beaucoup pour ton code! Je teste ça tout de suite!

  6. #6
    Membre émérite
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Par défaut
    ça marche! Merci encore Gojir4!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. WM17 Android NFC
    Par gregcoco dans le forum Windev Mobile
    Réponses: 1
    Dernier message: 06/01/2013, 13h56
  2. Tag vide en XML c'est quoi le standard ?
    Par parou dans le forum XML/XSL et SOAP
    Réponses: 2
    Dernier message: 16/06/2009, 11h58
  3. [DOM] probleme avec les tags vides
    Par epeichette dans le forum Bibliothèques et frameworks
    Réponses: 4
    Dernier message: 20/01/2009, 15h04
  4. Réponses: 3
    Dernier message: 04/12/2007, 10h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo