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

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    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!
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

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

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    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 éprouvé
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Nord (Nord Pas de Calais)

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    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!
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

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

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    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 éprouvé
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Nord (Nord Pas de Calais)

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Super merci beaucoup pour ton code! Je teste ça tout de suite!
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    ça marche! Merci encore Gojir4!
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  7. #7
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Citation Envoyé par michel.di Voir le message
    ça marche! Merci encore Gojir4!
    De rien! Content que ton problème soit résolu

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Dernière petite question
    J'ai une activité principale permettant d'écrire sur un tag lorsqu'il est passé.

    J'ai une activité qui se lance lorsqu'un tag est passé.

    Le soucis est que lorsque je passe un tag en étant dans l'activité principale, l'autre se lance.

    Il y a un moyen de bloquer ça?
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  9. #9
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Etrange phénomène effectivement. Peut être as-tu oublié d'appelé disableForegroundDispatch() dans la fonction onPause() ?
    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
    @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);
    	}
    Comment est lancé l'activité "secondaire" ? Par le biais de onCreate() ou de onNewIntent() ?

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Je vais mettre le code ce sera plus simple.
    Ce que j'aimerais faire, c'est que la MainActivity ne fasse juste qu'écrire sur le tag le message saisi dans un EditText et que le DiscoverActivity lise le contenu du tag lors du passage.

    le manifest :
    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
     
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dirix.leavemessage"
        android:versionCode="1"
        android:versionName="1.0" >
     
        <uses-sdk
            android:minSdkVersion="16"
            android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.NFC" />
     
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dirix.leavemessage.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
            android:name="com.dirix.leavemessage.DiscoverActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    	        <category android:name="android.intent.category.DEFAULT" />
    	        <data android:mimeType="*/*" />
            </intent-filter>
        </activity>
        </application>
     
    </manifest>
    MainActivity :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
     
    package com.dirix.leavemessage;
     
    import java.io.IOException;
    import java.nio.charset.Charset;
     
    import android.app.Activity;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.nfc.NdefMessage;
    import android.nfc.NdefRecord;
    import android.nfc.NfcAdapter;
    import android.nfc.Tag;
    import android.nfc.tech.Ndef;
    import android.nfc.tech.NdefFormatable;
    import android.os.Bundle;
    import android.widget.EditText;
    import android.widget.Toast;
     
    public class MainActivity extends Activity {
     
     
    	private NfcAdapter mNfcAdapter;
    	private IntentFilter[] mWriteTagFilters;
    	private PendingIntent mNfcPendingIntent;
    	private boolean writeProtect = false;
    	private Context context;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		context = getApplicationContext();
    		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    		mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
    				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
    				| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
    		IntentFilter discovery = new IntentFilter(
    				NfcAdapter.ACTION_TAG_DISCOVERED);
    		IntentFilter ndefDetected = new IntentFilter(
    				NfcAdapter.ACTION_NDEF_DISCOVERED);
    		IntentFilter techDetected = new IntentFilter(
    				NfcAdapter.ACTION_TECH_DISCOVERED);
    		// Intent filters for writing to a tag
    		mWriteTagFilters = new IntentFilter[] { discovery };
    	}
     
    	protected void onResume() {
    		super.onResume();
    		if (mNfcAdapter != null) {
    			if (!mNfcAdapter.isEnabled()) {
     
    			mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
    					mWriteTagFilters, null);
    			}
    		} else {
    			Toast.makeText(context, "Sorry, No NFC Adapter found.",
    					Toast.LENGTH_SHORT).show();
    		}
    	}
     
    	@Override
    	protected void onPause() {
    		super.onPause();
    		if (mNfcAdapter != null)
    			mNfcAdapter.disableForegroundDispatch(this);
    	}
     
    	@Override
    	protected void onNewIntent(Intent intent) {
    		super.onNewIntent(intent);
    		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
    			//getting id of the tag
     
    			// validate that this tag can be written
    			Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    			if (supportedTechs(detectedTag.getTechList())) {
    				// check if tag is writable (to the extent that we can
    				if (writableTag(detectedTag)) {
    					// writeTag here
    					WriteResponse wr = writeTag(getTagAsNdef(), detectedTag);
    					String message = (wr.getStatus() == 1 ? "Success: "
    							: "Failed: ") + wr.getMessage();
    					Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    				} else {
    					Toast.makeText(context, "This tag is not writable",
    							Toast.LENGTH_SHORT).show();
    				}
    			} else {
    				Toast.makeText(context, "This tag type is not supported",
    						Toast.LENGTH_SHORT).show();
    			}
    		}
    	}
     
    	public WriteResponse writeTag(NdefMessage message, Tag tag) {
    		int size = message.toByteArray().length;
    		String mess = "";
    		try {
    			Ndef ndef = Ndef.get(tag);
    			if (ndef != null) {
    				ndef.connect();
    				if (!ndef.isWritable()) {
    					return new WriteResponse(0, "Tag is read-only");
    				}
    				if (ndef.getMaxSize() < size) {
    					mess = "Tag capacity is " + ndef.getMaxSize()
    							+ " bytes, message is " + size + " bytes.";
    					return new WriteResponse(0, mess);
    				}
    				ndef.writeNdefMessage(message);
    				if (writeProtect)
    					ndef.makeReadOnly();
    				mess = "Wrote message to pre-formatted tag.";
    				return new WriteResponse(1, mess);
    			} else {
    				NdefFormatable format = NdefFormatable.get(tag);
    				if (format != null) {
    					try {
    						format.connect();
    						format.format(message);
    						mess = "Formatted tag and wrote message";
    						return new WriteResponse(1, mess);
    					} catch (IOException e) {
    						mess = "Failed to format tag.";
    						return new WriteResponse(0, mess);
    					}
    				} else {
    					mess = "Tag doesn't support NDEF.";
    					return new WriteResponse(0, mess);
    				}
    			}
    		} catch (Exception e) {
    			mess = "Failed to write tag";
    			return new WriteResponse(0, mess);
    		}
    	}
     
    	private class WriteResponse {
    		int status;
    		String message;
     
    		WriteResponse(int Status, String Message) {
    			this.status = Status;
    			this.message = Message;
    		}
     
    		public int getStatus() {
    			return status;
    		}
     
    		public String getMessage() {
    			return message;
    		}
    	}
     
    	public static boolean supportedTechs(String[] techs) {
    		boolean ultralight = false;
    		boolean nfcA = false;
    		boolean ndef = false;
    		for (String tech : techs) {
    			if (tech.equals("android.nfc.tech.MifareUltralight")) {
    				ultralight = true;
    			} else if (tech.equals("android.nfc.tech.NfcA")) {
    				nfcA = true;
    			} else if (tech.equals("android.nfc.tech.Ndef")
    					|| tech.equals("android.nfc.tech.NdefFormatable")) {
    				ndef = true;
    			}
    		}
    		if (ultralight && nfcA && ndef) {
    			return true;
    		} else {
    			return false;
    		}
    	}
     
    	private boolean writableTag(Tag tag) {
    		try {
    			Ndef ndef = Ndef.get(tag);
    			if (ndef != null) {
    				ndef.connect();
    				if (!ndef.isWritable()) {
    					Toast.makeText(context, "Tag is read-only.",
    							Toast.LENGTH_SHORT).show();
    					ndef.close();
    					return false;
    				}
    				ndef.close();
    				return true;
    			}
    		} catch (Exception e) {
    			Toast.makeText(context, "Failed to read tag", Toast.LENGTH_SHORT)
    					.show();
    		}
    		return false;
    	}
     
    	private NdefMessage getTagAsNdef() {
    		boolean addAAR = false;
    		EditText textView = (EditText)findViewById(R.id.message);
    		String uniqueId = textView.getEditableText().toString();
    		byte[] uriField = uniqueId.getBytes(Charset.forName("US-ASCII"));
    		byte[] payload = new byte[uriField.length + 1]; // add 1 for the URI
    														// Prefix
    		payload[0] = 0x01; // prefixes http://www. to the URI
    		System.arraycopy(uriField, 0, payload, 0, uriField.length); // appends
    																	// URI to
    																	// payload
    		NdefRecord rtdUriRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    				NdefRecord.RTD_TEXT, new byte[0], payload);
    		if (addAAR) {
    			// note: returns AAR for different app (nfcreadtag)
    			return new NdefMessage(new NdefRecord[] { rtdUriRecord,
    					NdefRecord.createApplicationRecord("com.dirix.leavemessage") });
    		} else {
    			return new NdefMessage(new NdefRecord[] { rtdUriRecord });
    		}
    	}
    }
    DiscoverActivity :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
     
    package com.dirix.leavemessage;
     
    import java.util.List;
     
    import org.ndeftools.Message;
    import org.ndeftools.Record;
    import org.ndeftools.externaltype.AndroidApplicationRecord;
     
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.nfc.NdefMessage;
    import android.nfc.NfcAdapter;
    import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
    import android.nfc.NfcEvent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Parcelable;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.widget.TextView;
    import android.widget.Toast;
     
     
    public class DiscoverActivity extends FragmentActivity implements OnNdefPushCompleteCallback{
     
    	private static final int MESSAGE_SENT = 1;
     
     
    	protected NfcAdapter nfcAdapter;
    	protected PendingIntent nfcPendingIntent;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.nfcreader);
    		Log.e("#########", "onCreate, action : " + getIntent().getAction());
    		// initialize NFC
    		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    		nfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
    				this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
     
    		// Register callback to listen for message-sent success
    		nfcAdapter.setOnNdefPushCompleteCallback(this, this);
     
    		if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) 
    				|| getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
    			TextView textView = (TextView) findViewById(R.id.title);
    			Log.e("######", "nfc tag read");
     
    			Parcelable[] messages = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    			if (messages != null) {
     
    				Log.d("#######", "Found " + messages.length + " NDEF messages"); // is almost always just one
     
     
    				// parse to records
    				for (int i = 0; i < messages.length; i++) {
    					try {
    						List<Record> records = new Message((NdefMessage)messages[i]);
     
    						Log.d("#######", "Found " + records.size() + " records in message " + i);
     
    						for(int k = 0; k < records.size(); k++) {
    							Log.d("#######", " Record #" + k + " is of class " + records.get(k).getClass().getSimpleName());
    							textView.setText(NfcUtils.bytesToHexString(records.get(k).getNdefRecord().getPayload()));
    		                    if(records.get(k) instanceof AndroidApplicationRecord) {
    								AndroidApplicationRecord aar = (AndroidApplicationRecord)records.get(k);
    								Log.d("#######", "Package is " + aar.getPackageName());
    							}
     
    						}
    					} catch (Exception e) {
    						Log.e("#######", "Problem parsing message", e);
    					}
     
     				}
    			}
    		}
    	}
     
    	@Override
    	protected void onResume() {
     
    		super.onResume();
     
    		enableForegroundMode();
    	}
     
    	@Override
    	protected void onPause() {
     
    		super.onPause();
     
    		disableForegroundMode();
    	}
     
     
     
    	public void enableForegroundMode() {
     
    		IntentFilter tagDetected = new IntentFilter(
    				NfcAdapter.ACTION_TAG_DISCOVERED); // filter for all
    		IntentFilter[] writeTagFilters = new IntentFilter[] { tagDetected };
    		nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent,
    				writeTagFilters, null);
    	}
     
    	public void disableForegroundMode() {
     
    		nfcAdapter.disableForegroundDispatch(this);
    	}
     
    	@Override
    	public void onNdefPushComplete(NfcEvent arg0) {
     
    		// A handler is needed to send messages to the activity when this
    		// callback occurs, because it happens from a binder thread
    		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
    	}
     
    	private final Handler mHandler = new Handler() {
    		@Override
    		public void handleMessage(android.os.Message msg) {
    			switch (msg.what) {
    			case MESSAGE_SENT:
    				Toast.makeText(getApplicationContext(), "Message beamed!", Toast.LENGTH_LONG).show();
    				break;
    			}
    		}
    	};	
    }
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  11. #11
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Je dois dire que je sèche. Je ne vois pas de raison pour que DiscoverActivity soit appelé alors que MainActivity est affichée, normalement cette dernière devrait être la seule à recevoir l'appel de onNewIntent(). J'en reviens à ma question :
    Comment est lancé l'activité DiscoverActivity ? Par le biais de onCreate() ou de onNewIntent() ?

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Je ne lance jamais directement la DiscoverActivity puisque j'aimerais qu'elle se lance lors de la lecture d'un tag lorsque l'appli est fermée
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  13. #13
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Citation Envoyé par michel.di Voir le message
    Le soucis est que lorsque je passe un tag en étant dans l'activité principale, l'autre se lance.

    Il y a un moyen de bloquer ça?
    Si j'ai bien compris, l'activité principale, c'est MainActivity, et DiscoverActivity est lancé lorsque tu scan un tag et que MainActivity est affichée ? juste ?
    D'où ma question.

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Non DiscoverActivity doit se lancer lorsque MainActivity n'est pas affichée
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  15. #15
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Ok j'avais compris l'inverse. Dans ce cas cela doit lancer l'application ? Si oui dans ce cas il faut ajouter ceci dans le manifest (en bleu) et voir si cela change quelque chose:
    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
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dirix.leavemessage"
        android:versionCode="1"
        android:versionName="1.0" >
     
        <uses-sdk
            android:minSdkVersion="16"
            android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.NFC" />
     
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dirix.leavemessage.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
            android:name="com.dirix.leavemessage.DiscoverActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    	        <category android:name="android.intent.category.DEFAULT" />
    	        <data android:mimeType="*/*" />
            </intent-filter>
            <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/techs" />
    
                <intent-filter>
                    <action android:name="android.nfc.action.TAG_DISCOVERED" />
    
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
        </activity>
        </application>
     
    </manifest>

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Quand je passe le tag sans appli de lancée, une autre appli se lance en disant "type de tag inconnu".
    Lorsque que je suis dans la MainActivity et que je passe le tag pour écrire dessus, j'ai le même soucis de "type de tag inconnu"...
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  17. #17
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    L'autre application qui se lance n'est elle pas définie par défaut lorsqu'un tag est scanné ?
    Sinon pour ce qui est du message "Type de tag inconnu" dans la MainActivity, n'est-ce pas toi qui le génère ici ?
    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
    @Override
    	protected void onNewIntent(Intent intent) {
    		super.onNewIntent(intent);
    		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
    			//getting id of the tag
     
    			// validate that this tag can be written
    			Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    			if (supportedTechs(detectedTag.getTechList())) {
    				...				
    			} else {
    				Toast.makeText(context, "This tag type is not supported",
    						Toast.LENGTH_SHORT).show();
    			}
    		}
    	}

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Non je n'ai pas mis d'appli par défaut pour les tags.

    Et non ça ne vient pas de là, ce n'est pas juste un message qui s'affiche mais une appli qui se lance.
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  19. #19
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2010
    Messages
    248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

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

    Informations forums :
    Inscription : Mai 2010
    Messages : 248
    Points : 421
    Points
    421
    Par défaut
    Et peut être un AAR dans le tag ? Sinon je ne vois pas dsl.

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

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

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    Je vais regarder ça. Merci en tous cas
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

+ 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