Android Open Source - AndroidNdefImplementation Nfc Ndef Reader






From Project

Back to project page AndroidNdefImplementation.

License

The source code is released under:

GNU General Public License

If you think the Android project AndroidNdefImplementation listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package fr.oversimple.nfc.ndefReader;
//  www.j a  v  a2  s  .  co m
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.util.Log;

/**
 * Add to the manifest : <uses-permission android:name="android.permission.NFC"
 * />
 * 
 * <uses-feature android:name="android.hardware.nfc" android:required="true" />
 * 
 * Don't forget to add the xml/nfc_tech_filter.xml to your project
 * 
 * and to add :
 * 
 * <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" />
 * 
 * <category android:name="android.intent.category.DEFAULT" />
 * 
 * <data android:mimeType="text/plain" /> </intent-filter>
 * 
 * <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
 * android:resource="@xml/nfc_tech_filter" />
 * 
 * to your activity in the AndroidManifest.xml file
 * 
 * @author Julien Hatin
 * 
 */
public class NfcNdefReader {

  private static final String TAG = "NfcUrlReader";
  private static final String MIME_TEXT_PLAIN = "text/plain";

  private NfcAdapter nfcAdapter;
  private NfcNdefReaderListener listener;

  public NfcNdefReader(Context context) {
    nfcAdapter = NfcAdapter.getDefaultAdapter(context);
  }

  public boolean isNfcActivated() {
    if (nfcAdapter == null) {
      return false;
    } else {
      return nfcAdapter.isEnabled();
    }
  }

  public boolean isNfcAvailableOnDevice() {
    if (nfcAdapter == null) {
      return false;
    } else {
      return true;
    }
  }

  public 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)) {
        Log.d(TAG, "Reading: " + 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;
        }
      }
    }
  }

  public void stopForegroundDispatch(Activity activity) {
    nfcAdapter.disableForegroundDispatch(activity);
  }

  public void setupForegroundDispatch(Activity activity) {
    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 (MalformedMimeTypeException e) {
      throw new RuntimeException("Check your mime type.");
    }
    nfcAdapter.enableForegroundDispatch(activity, pendingIntent, filters,
        techList);
  }

  public void setNfcUrlReaderListener(NfcNdefReaderListener listener) {
    this.listener = listener;
  }

  /**
   * Background task for reading the data. Do not block the UI thread while
   * reading.
   * 
   * @author Ralf Wondratschek
   * 
   */
  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 = ((payload[0] & 128) == 0) ? "UTF-8"
          : "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);
    }

    @Override
    protected void onPostExecute(String result) {
      if (null != result && null != listener) {
        listener.ndefDataRead(result);
      }
    }
  }

}




Java Source Code List

fr.oversimple.nfc.ndefReader.MainActivity.java
fr.oversimple.nfc.ndefReader.NfcNdefReaderListener.java
fr.oversimple.nfc.ndefReader.NfcNdefReader.java