lunedì 9 settembre 2013

Lettura di RFID Mifare con API di Android

In questo post viene descritto come leggere i tag Rfid Mifare Classic (13.56 MHz) disponendo di un telefono con antenna NFC come il Nexus S (attenzione che per leggere



L'interno con l'hardware NFC di un Nexus S (IFixIt)


Si parte da un progetto vuoto (Hello World) e si effettuano le modeste modifiche indicate in giallo nel listato seguente


Per prima cosa si deve modificare il file Manifest per dichiarare l'uso del sensore NFC e si deve dichiare una nuova intent che si apre quando viene passato un tag sotto il lettore

Manifest.xml
------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test4"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16" />

    <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.example.test4.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:label="@string/event_verify" android:name="verifytagscanact">
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED"/>
            </intent-filter>
            <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/filter_nfc"/>
        </activity>

    </application>

</manifest>
------------------------------------------------
Si deve creare poi una nuova cartella xml nelle risorse e si crea un nuovo file filter_nfc

/xml/filter_nfc.xml
------------------------------------------------
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.NfcA</tech>
        <tech>android.nfc.tech.MifareClassic</tech>
    </tech-list>
</resources>
------------------------------------------------

la Main Activity e' composta da un solo Adapter che apre una nuova intent. A questo punto si apre la funzione OnNewIntent che legge il contenuto del tag

MainActivity.java
------------------------------------------------
package com.example.test4;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.nfc.Tag;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.util.Log;
import android.widget.Toast;
import java.math.BigInteger;

public class MainActivity extends Activity {

    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    String[][] techListsArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adapter = NfcAdapter.getDefaultAdapter(this);

        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            tagDetected.addDataType("*/*");
        }
        catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };

        techListsArray = new String[][] { new String[] { MifareClassic.class.getName() } };

    }

    static String bin2hex(byte[] data) {
        return String.format("%0" + (data.length * 2) + "X", new BigInteger(1,data));
    }

    @Override
    protected void onNewIntent(Intent intent){
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
        Toast.makeText(getApplicationContext(), bin2hex(tag.getId()), Toast.LENGTH_SHORT).show();


    }

    public void onPause() {
        super.onPause();
        adapter.disableForegroundDispatch(this);
    }

    public void onResume() {
        super.onResume();
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, techListsArray);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


------------------------------------------------


Nessun commento:

Posta un commento

Riparazione volante Logitech G920

Con il tempo la pedaliera del Logitech G920 ha cominciato a fare i capricci in particolare per quanto riguarda l'acceleratore Ho provato...