package at.renehollander.schnitzeljagd.sensor; /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.annotation.TargetApi; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.os.Build; import android.util.Log; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; /** * Callback class, invoked when an NFC card is scanned while the device is running in reader mode. * <p> * Reader mode can be invoked by calling NfcAdapter */ @TargetApi(Build.VERSION_CODES.KITKAT) public class NFCReader implements NfcAdapter.ReaderCallback { private static final String TAG = "NFCReader"; // Weak reference to prevent retain loop. mAccountCallback is responsible for exiting // foreground mode before it becomes invalid (e.g. during onPause() or onStop()). private WeakReference<AccountCallback> mAccountCallback; public interface AccountCallback { void onAccountReceived(String account); } public NFCReader(AccountCallback accountCallback) { mAccountCallback = new WeakReference<AccountCallback>(accountCallback); } /** * Callback when a new tag is discovered by the system. * <p> * <p>Communication with the card should take place here. * * @param tag Discovered tag */ @Override public void onTagDiscovered(Tag tag) { Log.i(TAG, "New tag discovered"); this.readTextFromTag(tag); } private void readTextFromTag(Tag tag) { Ndef ndefTag = Ndef.get(tag); NdefMessage ndefMessage = ndefTag.getCachedNdefMessage(); NdefRecord[] ndefRecords = ndefMessage.getRecords(); if (ndefRecords != null && ndefRecords.length > 0) { NdefRecord ndefRecord = ndefRecords[0]; String tagContent = getTextFromNdefRecord(ndefRecord); Log.i(TAG, "Received: " + tagContent); mAccountCallback.get().onAccountReceived(tagContent); } else { Log.i(TAG, "No NDEF records found"); } } private static String getTextFromNdefRecord(NdefRecord ndefRecord) { String tagContent = null; try { byte[] payload = ndefRecord.getPayload(); String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; int languageSize = payload[0] & 0063; tagContent = new String(payload, languageSize + 1, payload.length - languageSize - 1, textEncoding); } catch (UnsupportedEncodingException e) { Log.e("getTextFromNdefRecord", e.getMessage(), e); } return tagContent; } }