@Override public void onTagDiscovered(final Tag tag) { Log.d(TAG, "Tag found: " + tag.toString()); Log.d(TAG, "Id: " + HexStrings.toHexString(tag.getId())); for (String tech: tag.getTechList()) { Log.d(TAG, "Tech: " + tech); } if (Arrays.asList(tag.getTechList()).contains("android.nfc.tech.IsoDep")) { IsoDepApduInterface apduInterface; try { apduInterface = new IsoDepApduInterface(IsoDep.get(tag)); } catch (IOException e) { fail(e.getMessage()); e.printStackTrace(); return; } dispatchLoadTask(apduInterface); } }
@Override public void onNewIntent(Intent intent) { String action = intent.getAction(); // Log.i("!intent! ", action); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] id = tag.getId(); String serialNumber = bytesToHex(id); WritableMap idData = Arguments.createMap(); idData.putString("id", serialNumber); sendEvent(this.reactContext, "NFCCardID", idData); }
private void formatTag(Tag tag, NdefMessage ndefMessage) { try { NdefFormatable ndefFormatable = NdefFormatable.get(tag); if (ndefFormatable == null) { Toast.makeText(this, "Tag is not formatable", Toast.LENGTH_LONG).show(); } ndefFormatable.connect(); ndefFormatable.format(ndefMessage); ndefFormatable.close(); } catch (Exception e) { Log.e("formatTag", e.getMessage()); } }
@Override public void onNewIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String[] techList = tag.getTechList(); boolean haveMifareUltralight = false; for (String tech : techList) { if (tech.indexOf("MifareUltralight") >= 0) { haveMifareUltralight = true; break; } } if (!haveMifareUltralight) { Toast.makeText(this, "不支持MifareUltralight数据格式", Toast.LENGTH_SHORT).show(); return; } writeTag(tag); }
@Override public void onNewIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String[] techList = tag.getTechList(); boolean haveMifareUltralight = false; for (String tech : techList) { if (tech.indexOf("MifareUltralight") >= 0) { haveMifareUltralight = true; break; } } if (!haveMifareUltralight) { Toast.makeText(this, "不支持MifareUltralight数据格式", Toast.LENGTH_SHORT).show(); return; } String data = readTag(tag); if (data != null) Toast.makeText(this, data, Toast.LENGTH_SHORT).show(); }
public void onNewIntent(Intent intent) { Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{createUriRecord(mUri)}); boolean result = writeTag(ndefMessage, detectedTag); if (result) { Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "写入失败", Toast.LENGTH_SHORT).show(); } }
/** * 写入标签 * * @param message * @param tag * @return */ public static boolean writeTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { return false; } if (ndef.getMaxSize() < size) { return false; } ndef.writeNdefMessage(message); return true; } } catch (Exception e) { } return false; }
private void connect(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (getIntent() == null) { // Lost Tag clean(callbackContext, "No tag available."); return; } final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { clean(callbackContext, "No tag available."); return; } try { Log.i(TAG, "Tag is: " + tag); mifareUltralight.connect(tag); callbackContext.success(); } catch (final Exception e) { clean(callbackContext, e); } } }); }
private void unlock(final CallbackContext callbackContext, final int pin) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (getIntent() == null) { // Lost Tag clean(callbackContext, "No tag available."); return; } final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { clean(callbackContext, "No tag available."); return; } try { mifareUltralight.unlockWithPin(pin); callbackContext.success(); } catch (final Exception e) { clean(callbackContext, e); } } }); }
private void parseMessage() { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Log.d(TAG, "parseMessage " + getIntent()); Intent intent = getIntent(); String action = intent.getAction(); Log.d(TAG, "action " + action); if (action == null) { return; } Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { fireTagEvent(tag, "mifareTagDiscovered"); } setIntent(new Intent()); } }); }
/** * To be executed on onNewIntent of activity * @param intent */ public void onActivityNewIntent(Intent intent) { // TODO Check if the following line has any use // activity.setIntent(intent); if (textToWrite == null) readTagFromIntent(intent); else { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try { writeTag(activity, tag, textToWrite); onTagWriteListener.onTagWritten(); } catch (NFCWriteException exception) { onTagWriteErrorListener.onTagWriteError(exception); } finally { textToWrite = null; } } }
private void handleIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { String type = intent.getType(); if (type.equals("application/vnd.bluetooth.ep.oob")) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); new NdefReaderTask().execute(tag); } else { Log.d(TAG, "Wrong mime type: " + type); } } }
private void resolveIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage[] msgs; if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { // Unknown tag type //byte[] empty = new byte[0]; //byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); showTagId(tag); //byte[] payload = dumpTagData(tag).getBytes(); //NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload); //NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); //msgs = new NdefMessage[] { msg }; } // Setup the views //buildTagViews(msgs); } }
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) { Toast.makeText(this, "NfcIntent!", Toast.LENGTH_SHORT).show(); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefMessage ndefMessage = createNdefMessage("My string content!"); writeNdefMessage(tag, ndefMessage); } }
/** * Callback when a new tag is discovered by the system. * * <p>Communication with the card should take place here. * * @param tag Discovered tag */ public void onTagDiscovered(Tag tag){ LogUtil.i(TAG, "======= Discovered Tag:" + tag + "=========="); // Android's Host-based Card Emulation (HCE) feature implements the ISO-DEP (ISO 14443-4) // protocol. // // In order to communicate with a device using HCE, the discovered tag should be processed // using the IsoDep class. mIsoDep = IsoDep.get(tag); // Connect to the remote NFC device try { mIsoDep.connect(); } catch (IOException e) { e.printStackTrace(); } mIsoDep.setTimeout(TIMEOUT); }
@Override public void onTagDiscovered(Tag tag) { Log.d(TAG, "onTagDiscovered: " + tag); final long startTime = System.currentTimeMillis(); long duration; try { IsoDep isoDep = IsoDep.get(tag); isoDep.connect(); onTagDiscovered(tag, isoDep, true); } catch (Throwable e) { Log.e(TAG, "Exception in onTagDiscovered", e); getPaymentRequestDelegate().onPaymentError(e.getMessage()); } }
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try { CardBalance balance = Readers.getInstance().readTag(tag); if (balance != null) { Log.d(DEBUG_TAG, balance.toString()); Intent broadcast = new Intent(CardBalance.ACTION_CARD_BALANCE); broadcast.putExtras(balance.toBundle()); sendBroadcast(broadcast); } } catch (DesfireException ignored) { // Card is not supported } } finish(); }
private void resolveIntent(Intent data, boolean foregroundDispatch) { this.setIntent(data); scan = true; String action = data.getAction(); if ((data.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { return; } if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)){ Tag tag = data.getParcelableExtra(NfcAdapter.EXTRA_TAG); Date now = new Date(); if (foregroundDispatch && (now.getTime() - last_scan.getTime()) > 10000) { //10000 = 10sec String[] techList = tag.getTechList(); String searchedTech = NfcV.class.getName(); // ###################### read Tag ###################### ProgressBar pb_scan; pb_scan = (ProgressBar)findViewById(R.id.pb_reading_spin); pb_scan.setVisibility(View.VISIBLE); new NfcVReaderTask(this).execute(tag); // ###################################################### } } }
@Override public void tagDiscovered(Tag tag) { try { nfcCard = AndroidCard.get(tag); if (pendingOperations.isEmpty()) { log("NFC Card attached. Awaiting for connection"); } else { log("NFC Card attached. Processing pending operations"); } processPendingCardOperations(); } catch (IOException e) { e.printStackTrace(); } }
/** * Creates a transceiver for the specified tag. * @return null is returned if a transceiver could not be created */ public static Transceiver create(Logger logger, Tag tag) { IsoDep isoDep = IsoDep.get(tag); if (null == isoDep) { logger.warn(TAG, "Unable to create IsoDep for NFC tag: " + StringUtil.join(tag.getTechList(), ", ")); return null; } logger.info(TAG, "Connnecting to ISO-DEP: " + isoDep.isConnected()); try { isoDep.connect(); isoDep.setTimeout(30000); return new Transceiver(logger, isoDep); } catch (Exception ex) { logger.error(TAG, "Unable to connect to ISO-DEP", ex); return null; } }
protected void handleIntent(Intent intent) { if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { Tag discoveredTag; discoveredTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try { if(discoveredTag != null){ if(validate()) { writeTAG(discoveredTag); postNFC(); } } } catch (Exception e) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.alert_title_error)); alert.setMessage(getString(R.string.alert_error_nfc)); alert.setPositiveButton(getString(R.string.ok), null); alert.show(); } } }
protected void writeTAG(Tag tag) throws IOException, FormatException { Ndef ndefTag = Ndef.get(tag); byte[] stringBytes = passphrase.getBytes(); NdefRecord data = NdefRecord.createMime(CONST.NFC_MIME_LOGIN, stringBytes); NdefMessage message = new NdefMessage(data); if (ndefTag != null) { //write to formatted tag ndefTag.connect(); ndefTag.writeNdefMessage(message); } else { //format the tag NdefFormatable format = NdefFormatable.get(tag); if(format != null) { format.connect(); format.format(message); } } }
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); try { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Card card = new CardParser().parse(tag); if (card != null) { Intent resultIntent = new Intent(); resultIntent.putExtra(EXTRA_CARD, card); setResult(Activity.RESULT_OK, resultIntent); finish(); } } catch (Exception e) { Journal.log(e); setResult(RESULT_ERROR); finish(); } }
public String nfcRead(Tag t) { Tag tag = t; Ndef ndef = Ndef.get(tag); if (ndef == null) { 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) {} } } return null; }
public void nfcReader(Tag tag) { nfcSubscription=Observable.just(nfcRead(tag)) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { if (s != null) { lblNFCID.setText(s); } } }); }
@Override protected NFCTag doInBackground(Intent... params) { Intent intent = params[0]; Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Ndef ndef = Ndef.get(tag); if (ndef == null) { return null; } NdefMessage ndefMessage = ndef.getCachedNdefMessage(); if(ndefMessage != null) { NdefRecord[] records = ndefMessage.getRecords(); for (NdefRecord ndefRecord : records) { try { return new NFCTag(ndefRecord).decode(); } catch (UnsupportedEncodingException e) { Log.e("NFC", "Unsupported Encoding", e); } } } return null; }
@Override protected void onNewIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Log.d(TAG, "onNewIntent: "+intent.getAction()); if(tag != null) { Toast.makeText(this, getString(R.string.message_tag_detected), Toast.LENGTH_SHORT).show(); Ndef ndef = Ndef.get(tag); if (isDialogDisplayed) { if (isWrite) { String messageToWrite = mEtMessage.getText().toString(); mNfcWriteFragment = (NFCWriteFragment) getFragmentManager().findFragmentByTag(NFCWriteFragment.TAG); mNfcWriteFragment.onNfcDetected(ndef,messageToWrite); } else { mNfcReadFragment = (NFCReadFragment)getFragmentManager().findFragmentByTag(NFCReadFragment.TAG); mNfcReadFragment.onNfcDetected(ndef); } } } }
public void writeTag(Tag tag, NdefMessage message) { if (tag != null) { try { Ndef ndefTag = Ndef.get(tag); if (ndefTag == null) { // Let's try to format the Tag in NDEF NdefFormatable nForm = NdefFormatable.get(tag); if (nForm != null) { nForm.connect(); nForm.format(message); nForm.close(); } } else { ndefTag.connect(); ndefTag.writeNdefMessage(message); ndefTag.close(); } } catch(Exception e) { e.printStackTrace(); } } }
protected void onNewIntent(Intent intent) { //called when a new tag is read. //Writes the held message when a tag is scanned if (message==null) { Toast.makeText(this, "Message was not defined, did not write", Toast.LENGTH_SHORT).show(); } Toast.makeText(this, "Writing to Tag", Toast.LENGTH_SHORT).show(); Tag currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (message != null) { nfcHandler.writeTag(currentTag, message); } StatusText.setText("Written to tag!"); StatusText.setTextColor(Color.GREEN); }
/** * Writes an NdefMessage to a NFC tag */ public static void writeTag(NdefMessage message, Tag tag) throws Exception { int size = message.toByteArray().length; Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { throw new NfcTagNotWritableException(); } if (ndef.getMaxSize() < size) { throw new NfcTagInsufficientMemoryException(ndef.getMaxSize(), size); } ndef.writeNdefMessage(message); } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { format.connect(); format.format(message); } else { throw new IllegalArgumentException("Ndef format is NULL"); } } }
@Override protected ArrayList<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; } ArrayList<String> results = new ArrayList<>(); 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 { results.add(readText(ndefRecord)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported Encoding", e); } } } return results; }
public static boolean writableTag(Tag tag) { try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { ndef.close(); return false; } ndef.close(); return true; } } catch (Exception e) { } return false; }
@Override public void onEnter(State fromState, Enum<?> event, Object data) { if (fromState.getClass().equals(DetectingState.class)) { mNFCDetectView.get().onViewStateChange(NFCDetectView.State.WRITING); Tag detectedTag = (Tag) data; Context context = mNFCDetectView.get().getContext(); if (NFCHelper.supportedTechs(detectedTag.getTechList())) { if (NFCHelper.writableTag(detectedTag)) { //writeTag here NdefMessage message = NFCHelper.createNdefTextAppMessage(context, mNFCDetectView.get().getTargetContent()); new NfcWriteNdefAsyncTask(NFCDetectPresenter.this, detectedTag).execute(message); } else { mStateMachine.postEvent(EVENT.FINISH, NfcWriteNdefAsyncTask.Result.READONLY); } } else { mStateMachine.postEvent(EVENT.FINISH, NfcWriteNdefAsyncTask.Result.UNSUPPORTED); } } }
@Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Log.d(TAG, "onResume"); Intent intent = getIntent(); if (intent.getAction().equals("android.intent.action.VOICE_COMMAND")) { Intent voiceIntent = new Intent(INTENT_VOICE_COMMAND); startActivity(voiceIntent); } else if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { if (PrefUtil.getbooleanValue(getApplicationContext(), "pref_nfc_cmd_enable", true)) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); new NfcReadNdefAsyncTask(getApplicationContext()).execute(tag); } finish(); } }
private void readTag(Tag t) { byte[] id = t.getId(); // get NDEF tag details Ndef ndefTag = Ndef.get(t); // get NDEF message details NdefMessage ndefMesg = ndefTag.getCachedNdefMessage(); if (ndefMesg == null) { return; } NdefRecord[] ndefRecords = ndefMesg.getRecords(); if (ndefRecords == null) { return; } for (NdefRecord record : ndefRecords) { short tnf = record.getTnf(); String type = new String(record.getType()); if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) { String url = new String(record.getPayload()); recordBadge(url); } } }
void onActivityNewIntent(Intent intent) { if (nfcAdapter != null) { // activity.setIntent(intent); //if (writeText == null) readTagFromIntent(intent); //else { if (writeText != null)/* && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()))*/ { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try { writeTag(/*activity, */tag, writeText); onTagWriteListener.onTagWritten(); } catch (NFCTagWriteException exception) { onTagWriteErrorListener.onTagWriteError(exception); } finally { writeText = null; } } } }
private void readTagFromIntent(Intent intent) { if (intent != null){ String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { tagReaded = true; // get NDEF tag details Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag != null) { Ndef ndefTag = Ndef.get(tag); //int tagSize = ndefTag.getMaxSize(); // tag size tagIsWritable = ndefTag.isWritable(); // is tag writable? //String tagType = ndefTag.getType(); // tag type Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { NdefRecord[] records = ((NdefMessage) rawMsgs[0]).getRecords(); String text = ndefRecordToString(records[0]); onTagReadListener.onTagRead(text); } } } } }
@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; }
public static AndroidCard get(Tag tag) throws IOException { IsoDep card = IsoDep.get(tag); if(card != null) { /* Workaround for the Samsung Galaxy S5 (since the * first connection always hangs on transceive). * TODO: This could be improved if we could identify * Samsung Galaxy S5 devices */ card.connect(); card.close(); return new AndroidCard(card); } else { return null; } }