Partage
  • Partager sur Facebook
  • Partager sur Twitter

NFC Android

Anonyme
    10 février 2016 à 11:21:12

    Bonjour,

    J'ai récemment commencé à développer une application qui entre autres nécessite le NFC (Pour l'ouverture de l'application en fait, on arrive sur un écran d'accueil, on scan la puce et ça déverouille).

    J'ai donc fait pas mal de recherches, mais aucune des solutions que j'ai utilisé n'ont fonctionné, j'ai parcouru et tenté une bonne dizaine de solutions différentes, et j'ai fini par celle donnée sur le site Android (Code joint).

    Pourtant, alors que avant ça ne fonctionnait pas, maintenant lorsque je scan ça me donne cette erreur: "NFC service dead - attempting to recover"

    Je voulais donc savoir comment faire pour récupérer les données stockées sur la puce NFC (capture d'écran du scan NFC Tools + lien de la page d'achat de la puce donnés à la fin).

    MainActivity.java

    package com.artemis.artemis;
    
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.res.Resources;
    import android.nfc.NfcAdapter;
    import android.nfc.Tag;
    import android.nfc.tech.MifareUltralight;
    import android.nfc.tech.NfcF;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.io.IOException;
    import java.nio.charset.Charset;
    
    public class MainActivity extends AppCompatActivity {
    
        private NfcAdapter nfc;
        public TextView banner;
        public IntentFilter[] intentFilterArray;
        public String[][] techListArray;
        public PendingIntent pendingIntent;
        public static final String MIME_TEXT_PLAIN = "text/plain", TAG = "NFC";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Resources res = getResources();
    
            String welcome_text = res.getString(R.string.welcome, "Artemis");
            banner = (TextView) findViewById(R.id.welcome);
            banner.setText(welcome_text);
    
            // Beginning of NFC Dedicated part
            nfc = NfcAdapter.getDefaultAdapter(this);
    
            if (nfc == null) {
                Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
                finish();
                return;
            }
            if (!nfc.isEnabled())
                Toast.makeText(this, "NFC is disabled on this device. Please turn it on before running the app.", Toast.LENGTH_LONG).show();
            else
                banner.setText("Scanning for NFC targets");
    
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    
            IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            try {
                ndef.addDataType("*/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                throw new RuntimeException("failed", e);
            }
    
            intentFilterArray = new IntentFilter[] {ndef, };
            techListArray = new String[][] { new String[] {NfcF.class.getName()}};
            // End of NFC Dedicated part
        }
    
        public String readTag(Tag tag) {
            MifareUltralight mifare = MifareUltralight.get(tag);
            try {
                mifare.connect();
                byte[] payload = mifare.readPages(4);
                return new String(payload, Charset.forName("US-ASCII"));
            } catch (IOException e) {
                Log.e(TAG, "IOException while reading the message..", e);
            } finally {
                if (mifare != null) {
                    try {
                        mifare.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Error closing tag..", e);
                    }
                }
            }
            return null;
        }
    
        @Override
        protected void onNewIntent(Intent in) {
            Tag tag = in.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            banner.setText(readTag(tag));
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            nfc.enableForegroundDispatch(this, pendingIntent, intentFilterArray, techListArray);
        }
    
        @Override
        protected void onPause() {
            nfc.disableForegroundDispatch(this);
            super.onPause();
        }
    }
    


    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.artemis.artemis" >
    
        <uses-permission android:name="android.permission.NFC" />
        <uses-feature android:name="android.hardware.nfc" android:required="true" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
                <intent-filter>
                    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <data android:mimeType="text/plain" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    


    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.artemis.artemis.MainActivity">
    
        <TextView
            android:id="@+id/welcome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:textAlignment="center"
            android:textSize="34sp"
            android:text="@string/welcome"/>
    
        <ImageView
            android:id="@+id/scan_to_unlock"
            android:layout_marginTop="150dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/image_desc"
            android:src="@drawable/scan_to_unlock"/>
    </RelativeLayout>
    


    NFC Tools:

    Partie 1: http://imgur.com/vU2ePX2

    Partie 2: http://imgur.com/rmR59zP

    Puce NFC: http://www.banggood.com/Intelligent-Smart-Magic-NFC-Ring-For-NFC-Android-Mobile-Phone-p-959218.html

    • Partager sur Facebook
    • Partager sur Twitter
    Anonyme
      10 février 2016 à 19:03:12

      Je sais que le NFCBeamShareData retournera un objet null si l'état de l'activité n'est pas resume.
      • Partager sur Facebook
      • Partager sur Twitter
      Anonyme
        10 février 2016 à 19:04:04

        C'est ce qui cause le service dead.
        • Partager sur Facebook
        • Partager sur Twitter
        Anonyme
          11 février 2016 à 10:34:11

          D'accord, mais concernant le NFC, une solution pour le faire fonctionner correctement ? (Code simple)
          • Partager sur Facebook
          • Partager sur Twitter
          Anonyme
            11 février 2016 à 16:33:29

            Comme ton message de départ indique que tu as suivi la documentation Google, après avoir réglé ce petit problème, tout devrait fonctionner correctement.

            Sinon dis nous quel message d'erreur ou quel résultat tu obtiens ?

            Merci :)

            • Partager sur Facebook
            • Partager sur Twitter
            Anonyme
              11 février 2016 à 20:51:41

              Alex112524 a écrit:

              Comme ton message de départ indique que tu as suivi la documentation Google, après avoir réglé ce petit problème, tout devrait fonctionner correctement.

              Sinon dis nous quel message d'erreur ou quel résultat tu obtiens ?

              Merci :)


              Message d'erreur: Aucun, le téléphone fait comme si il ne détectait pas le tag.

              Résultat: Rien ne bouge. Juste le bip annonçant la lecture d'un tag.

              • Partager sur Facebook
              • Partager sur Twitter
              Anonyme
                13 février 2016 à 5:00:46

                Bonjour,

                Voici enfin le topo que je t'avais promis sur le NFC :D

                Pour ceux qui sont atterris ici, à moins que cela ne soit par hasard, vous avez déjà une brève idée du concept, mais les recherches effectuées jusqu'à maintenant était floues >_<

                D'abord, un petit intro sur le sujet ! NFC (Near Field Communication) permet à deux appareils ou à un appareil et à une puce (aussi appelée tag) de communiquer ensemble. Ainsi, il est possible de :

                     1. Permettre à deux appareils Android supportant NFC d'échanger des fichiers sans contact.

                     2. Permettre la lecture et l'écriture du contenu d'une puce. Cette technique est notamment utilisée pour les applications portefeuilles (wallet apps)  qui permettent à l'utilisateur de payer avec son téléphone, ce dernier imitant le comportement de ses cartes bancaires.

                Je vais d'abord faire une démonstration du NFC à sa plus simple expression, soit la lecture d'une puce. Pour se faire, je débute avec un fichier XML classique auto-généré à la création d'un projet, ne contenant qu'un RelativeLayout et un TextView. De plus, j'ai en main un MainActivity qui ne contient que la méthode onCreate() avec son association à content_main.

                package com.alexandremartin.contentsharing;
                
                import android.app.Activity;
                
                public class MainActivity extends AppCompatActivity {
                
                
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.content_main);
                
                
                
                     }
                }
                

                MainActivity.java

                <?xml version="1.0" encoding="utf-8"?>
                
                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior"
                    tools:context="com.alexandremartin.contentsharing.MainActivity">
                
                
                    <TextView
                        android:layout_height="wrap_content"
                        android:layout_width="wrap_content" />
                
                
                </RelativeLayout>

                content_main.xml

                Il va y avoir plusieurs étapes, mais j'espère qu'elles seront toutes claires et concises :D

                1. Supporter une version minimale de 16

                L'utilisation de NFC demande un SDK minimal de 16. Il faut donc modifier cette information dans le Gradle (Module:app).

                   //...
                    defaultConfig {
                        applicationId "com.alexandremartin.contentsharing"
                        minSdkVersion 16 
                        targetSdkVersion 23
                        versionCode 1
                        versionName "1.0"
                    }
                    //...

                build.gradle(Module : app)

                2. Permissions

                Le NFC en soit est une permission que l'on doit obtenir. Pour utiliser la fonctionnalité de transfert de fichiers, il faudra éventuellement avoir la permission READ_EXTERNAL_STORAGE. La raison est simple : le partage d'un fichier requiert que ce dernier soit enregistré sur un support externe.

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

                AndroidManifest.xml

                3. Features (optionnel)

                Cette étape est optionnelle dans la mesure où elle ne doit être accomplie que si votre application dépend de la fonctionnalité NFC. Si vous vérifiez dans votre code la présence de la fonctionnalité et que vous êtes capable de répondre en cas d'absence, n'ajouter pas cette ligne de code. Grâce à elle, il n'y a que les appareils supportant NFC qui pourront retrouver votre application sur le marché Play Store.

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

                AndroidManifest.java

                4. Modifier le fichier XML de base

                Nous allons maintenant modifier un peu le fichier XML. Pour la lecture d'une puce, j'aurai besoin de conserver le TextView, mais il faut lui ajouter un id et un text

                    <TextView
                        android:id="@+id/tvNFCInfo"
                        android:layout_height="wrap_content"
                        android:layout_width="wrap_content"
                        android:text="@string/nfc" />

                content_main.xml 

                <resources>
                    <string name="app_name">ContentSharing</string>
                    <string name="action_settings">Settings</string>
                    <string name="nfc">NFC enabled</string>
                </resources>

                strings.xml

                5. Sérialiser le TextView

                Pour plusieurs d'entre vous, cette étape semble évidente et elle est probablement déjà accomplie par habitude, mais je voulais tout de même la mentionner :D

                private TextView tvNFCInfo;
                
                //...
                
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.content_main);
                
                        tvNFCInfo = (TextView) findViewById(R.id.tvNFCInfo);
                
                       //...

                MainActivity.java

                6. Créer un NFC Adapter

                private NfcAdapter nfcAdapter;
                
                //...
                
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.content_main);
                
                        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
                
                        //...

                MainActivity.java

                7. S'assurer que l'appareil est prêt à l'emploi

                Depuis Android 6.0, l'utilisation des permissions a changée. Bien qu'elles doivent être définies dans le Manifest, elles doivent en plus être vérifiées durant l'utilisation de l'application. Ainsi, au lieu de les confirmer à l'installation, l'usager les confirme à l'utilisation des fonctionnalités. Pour être plus clair, si on télécharge votre application, mais qu'on ne l'utilise jamais, la permission ne sera pas demandée.

                On doit également vérifier que la version de l'appareil est suffisante et que le NFC est activé. Voici le code sans plus tarder, il parle beaucoup de lui-même ;) :

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.content_main);
                
                        //...
                
                        PackageManager pm = this.getPackageManager();
                
                        //Ask for NFC permission
                        if (checkSelfPermission(Manifest.permission.NFC) == PackageManager.PERMISSION_GRANTED) {
                            // Check whether NFC is available on device
                            if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
                                // NFC is not available on the device.
                                Toast.makeText(this, "The device does not have NFC hardware.",
                                        Toast.LENGTH_SHORT).show();
                            }
                            // Check whether device is running Android 4.1 or higher
                            else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                
                                // Android Beam feature is not supported.
                                Toast.makeText(this, "Android Beam is not supported.",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                // NFC and Android Beam file transfer are supported.
                                Toast.makeText(this, "Android Beam is supported on your device.", Toast.LENGTH_SHORT).show();
                
                                if (!nfcAdapter.isEnabled()) {
                                    tvNFCInfo.setText("NFC is disabled.");
                                } else {
                                    tvNFCInfo.setText(R.string.nfc);
                                }
                            }
                
                        }
                
                    }

                MainActivity.java

                8. Si tout va bien, on va préparer l'application à réagir lors d'une lecture

                    private void handleIntent(Intent intent) {
                        // TODO: handle Intent
                
                
                    }

                MainActivity.java

                Cette méthode va après le onCreate(). On va la définir et l'utiliser plus tard...

                9. NFC Intent Filters

                En ordre de priorité, il existe trois Tags pour le NFC :

                     - ACTION_NDEF_DISCOVERED

                     - ACTION_TECH_DISCOVERED

                     - ACTION_TAG_DISCOVERED

                Et voici un graphique qui est moins bavard que moi, mais qui explique un peu mieux leur utilisation :p :

                Comme nous utiliserons le second, il se peut que l'Activity Chooser s'ouvre à la lecture de la puce. Il s'agit de cette fameuse boîte de dialogue qui demande à l'utilisateur l'application à utiliser pour gérer la situation. Si vous êtes chanceux, il choisira la vôtre :lol:.

                Les plus perspicaces d'entre-vous l'auront deviné, il faudra utiliser un Intent Filter pour notre MainActivity !

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

                AndroidManifest.xml


                Pour le meta-data, il faudra utiliser le fichier source suivant. Ce dernier est situé dans le dossier res/xml/ :

                <?xml version="1.0" encoding="utf-8"?>
                <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
                
                    <!--NFC step 9-->
                
                    <tech-list>
                        <tech>android.nfc.tech.Ndef</tech>
                        <!-- class name -->
                    </tech-list>
                </resources>

                nfc_tech_filter.xml

                10. Foreground dispatch

                Nous sommes presque prêts à effectuer la lecture, mais il y a un comportement qui est important à gérer avant !

                Lors de la lecture d'une puce, Android réouvre votre application pour afficher le résultat, ce qui augmente inutilement la pile d'activités >_< !

                Le Foreground dispatch sert à palier ce problème.

                    @Override
                    protected void onResume() {
                        super.onResume();
                
                        /**
                         * It's important, that the activity is in the foreground (resumed). Otherwise
                         * an IllegalStateException is thrown.
                         */
                        setupForegroundDispatch(this, nfcAdapter);
                    }
                
                    @Override
                    protected void onPause() {
                        /**
                         * Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
                         */
                        stopForegroundDispatch(this, nfcAdapter);
                
                        super.onPause();
                    }

                MainActivity.java

                Et voici les deux méthodes utilisées par ces méthodes de callback :

                    /**
                     * @param activity The corresponding {@link Activity} requesting the foreground dispatch.
                     * @param adapter The {@link NfcAdapter} used for the foreground dispatch.
                     */
                    public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
                        final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
                        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                
                        final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
                
                        IntentFilter[] filters = new IntentFilter[1];
                        String[][] techList = new String[][]{};
                
                        // Notice that this is the same filter as in our manifest.
                        filters[0] = new IntentFilter();
                        filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
                        filters[0].addCategory(Intent.CATEGORY_DEFAULT);
                        try {
                            filters[0].addDataType(MIME_TEXT_PLAIN);
                        } catch (IntentFilter.MalformedMimeTypeException e) {
                            throw new RuntimeException("Check your mime type.");
                        }
                
                        adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
                    }
                
                    /**
                     * @param activity The corresponding request to stop the foreground dispatch.
                     * @param adapter The {@link NfcAdapter} used for the foreground dispatch.
                     */
                    public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
                        adapter.disableForegroundDispatch(activity);
                    }

                MainActivity.java

                11. Réagir à la réception de l'intention

                Lorsque votre application reçoit l'Intent, c'est la méthode de callback onNewIntent() qui sera appelée. Il paraît maintenant évident que son rôle sera d'appeler la méthode handleIntent() que l'on va bientôt définir.

                    @Override
                    protected void onNewIntent(Intent intent) {
                        /**
                         * This method gets called, when a new Intent gets associated with the current activity instance.
                         * Instead of creating a new activity, onNewIntent will be called. For more information have a look
                         * at the documentation.
                         *
                         * In our case this method gets called, when the user attaches a Tag to the device.
                         */
                        handleIntent(intent);
                    }

                MainActivity.java

                12. Lecture des données

                On y arrive enfin ! On va effectuer en arrière-plan une suite de tâches permettant de lire l'information sur la puce.

                    public static final String MIME_TEXT_PLAIN = "text/plain";
                    public static final String TAG = "NfcDemo";

                MainActivity.java

                Voici l'appel au nouveau thread :

                    private void handleIntent(Intent intent) {
                
                        String action = intent.getAction();
                        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
                
                            String type = intent.getType();
                            if (MIME_TEXT_PLAIN.equals(type)) {
                
                                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                                new NdefReaderTask().execute(tag);
                
                            } else {
                                Log.d(TAG, "Wrong mime type: " + type);
                            }
                        } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
                
                            // In case we would still use the Tech Discovered Intent
                            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                            String[] techList = tag.getTechList();
                            String searchedTech = Ndef.class.getName();
                
                            for (String tech : techList) {
                                if (searchedTech.equals(tech)) {
                                    new NdefReaderTask().execute(tag);
                                    break;
                                }
                            }
                        }
                    }

                MainActivity.java

                Et son exécution :

                    /**
                     * Background task for reading the data. Do not block the UI thread while reading.
                     *
                     *
                     */
                    private class NdefReaderTask extends AsyncTask<Tag, Void, String> {
                
                        @Override
                        protected String doInBackground(Tag... params) {
                            Tag tag = params[0];
                
                            Ndef ndef = Ndef.get(tag);
                            if (ndef == null) {
                                // NDEF is not supported by this Tag.
                                return null;
                            }
                
                            NdefMessage ndefMessage = ndef.getCachedNdefMessage();
                
                            NdefRecord[] records = ndefMessage.getRecords();
                            for (NdefRecord ndefRecord : records) {
                                if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                                    try {
                                        return readText(ndefRecord);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, "Unsupported Encoding", e);
                                    }
                                }
                            }
                
                            return null;
                        }
                
                        private String readText(NdefRecord record) throws UnsupportedEncodingException {
                        /*
                         * See NFC forum specification for "Text Record Type Definition" at 3.2.1
                         *
                         * http://www.nfc-forum.org/specs/
                         *
                         * bit_7 defines encoding
                         * bit_6 reserved for future use, must be 0
                         * bit_5..0 length of IANA language code
                         */
                
                            byte[] payload = record.getPayload();
                
                            // Get the Text Encoding
                            String textEncoding;
                
                            if ((payload[0] & 128) == 0) {
                
                                textEncoding = "UTF-8";
                
                            } else {
                
                                textEncoding = "UTF-16";
                            }
                
                            // Get the Language Code
                            int languageCodeLength = payload[0] & 0063;
                
                            // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
                            // e.g. "en"
                
                            // Get the Text
                            return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
                        }
                
                //...
                
                }

                MainActivity.java

                13. Affichage de la valeur

                Maintenant, il ne reste plus qu'à donner cette valeur au TextView suite à l'exécution de la tâche (thread) :

                        @Override
                        protected void onPostExecute(String result) {
                            if (result != null) {
                                tvNFCInfo.setText("Read content: " + result);
                            }
                        }

                MainActivity.java

                C'est ce qui complète la première partie de la démonstration. La seconde vous apprendra à effectuer un transfert de fichier entre deux appareils, ce qu'on appelle aussi P2P (Peer-to-peer communication).

                14. Ajuster le layout

                Nous allons d'abord ajuster le layout afin qu'il soit possible d'effectuer le transfert lors d'un clic sur un bouton. La racine deviendra donc un LinearLayout vertical pour disposer les TextView et Button :

                <?xml version="1.0" encoding="utf-8"?>
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior"
                    tools:context="com.alexandremartin.contentsharing.MainActivity">
                
                    <TextView
                        android:id="@+id/tvNFCInfo"
                        android:layout_height="wrap_content"
                        android:layout_width="wrap_content"
                        android:text="@string/nfc" />
                
                    <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="8dp"
                        android:text="Send File"
                        android:onClick="sendFile" />
                
                
                </LinearLayout>
                

                content_main.xml

                15. La méthode sendFile()

                Il ne reste plus qu'à répondre au clic sur le bouton. Cette méthode effectuera le transfert d'une image d'un appareil à un autre.

                    public void sendFile(View view) {
                        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
                
                        // Check whether NFC is enabled on device
                        if(!nfcAdapter.isEnabled()){
                            // NFC is disabled, show the settings UI
                            // to enable NFC
                            Toast.makeText(this, "Please enable NFC.",
                                    Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
                        }
                        // Check whether Android Beam feature is enabled on device
                        else if(!nfcAdapter.isNdefPushEnabled()) {
                            // Android Beam is disabled, show the settings UI
                            // to enable Android Beam
                            Toast.makeText(this, "Please enable Android Beam.",
                                    Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
                        }
                        else {
                            // NFC and Android Beam both are enabled
                
                            // File to be transferred
                            // For the sake of this tutorial I've placed an image
                            // named 'wallpaper.png' in the 'Pictures' directory
                            String fileName = "wallpaper.png";
                
                            // Retrieve the path to the user's public pictures directory
                            File fileDirectory = Environment
                                    .getExternalStoragePublicDirectory(
                                            Environment.DIRECTORY_PICTURES);
                
                            // Create a new file using the specified directory and name
                            File fileToTransfer = new File(fileDirectory, fileName);
                            fileToTransfer.setReadable(true, false);
                
                            nfcAdapter.setBeamPushUris(
                                    new Uri[]{Uri.fromFile(fileToTransfer)}, this);
                        }
                    }

                MainActivity.java

                En espérant que ce tuto vous sera utile :D 

                N'hésitez pas à ajouter vos questions sur ce topic !

                -
                Edité par Anonyme 13 février 2016 à 5:01:33

                • Partager sur Facebook
                • Partager sur Twitter
                Anonyme
                  13 février 2016 à 15:13:48

                  Cette partie:

                  @Override
                      protected void onPostExecute(String r) {
                          if (r != null)
                              textview.setText("Content read: " + r);
                      }

                  S'insère où dans le code ?

                  Je l'ai insérée dans mon MainActivity, mais il me dit qu'il n'y a aucune méthode à override.

                  Voici mon code:

                  http://pastebin.com/LBvPGjCu

                  • Partager sur Facebook
                  • Partager sur Twitter
                  Anonyme
                    13 février 2016 à 16:18:24

                    Dans l'extrait de code juste avant celui du onPostExecute(), les trois petits points indiquent l'endroit pour mettre la méthode de callback :)

                    • Partager sur Facebook
                    • Partager sur Twitter

                    NFC Android

                    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                    • Editeur
                    • Markdown