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); } } }
private void writeToNfc(Ndef ndef, String message){ mTvMessage.setText(getString(R.string.message_write_progress)); if (ndef != null) { try { ndef.connect(); NdefRecord mimeRecord = NdefRecord.createMime("text/plain", message.getBytes(Charset.forName("US-ASCII"))); ndef.writeNdefMessage(new NdefMessage(mimeRecord)); ndef.close(); //Write Successful mTvMessage.setText(getString(R.string.message_write_success)); } catch (IOException | FormatException e) { e.printStackTrace(); mTvMessage.setText(getString(R.string.message_write_error)); } finally { mProgress.setVisibility(View.GONE); } } }
private void openFile(String filePath) throws Exception { if (filePath == null) { throw new FileNotFoundException("No file selected"); } File myFile = new File(filePath); if (!myFile.exists()) { throw new FileNotFoundException("Cannot find: " + myFile.toString()); } if (!myFile.canRead()) { throw new FormatException("Cannot open: " + myFile.toString()); } dfuFile.filePath = myFile.toString(); dfuFile.file = new byte[(int) myFile.length()]; //convert file into byte array FileInputStream fileInputStream = new FileInputStream(myFile); int readLength = fileInputStream.read(dfuFile.file); fileInputStream.close(); if (readLength != myFile.length()) { throw new IOException("Could Not Read File"); } }
public static SmartPosterRecord parseNdefRecord(NdefRecord ndefRecord) throws FormatException { byte[] payload = ndefRecord.getPayload(); normalizeMessageBeginEnd(payload); SmartPosterRecord smartPosterRecord = new SmartPosterRecord(); if(payload.length > 0) { List<Record> records = Message.parseNdefMessage(payload); for (Record record : records) { if (record instanceof UriRecord) { smartPosterRecord.setUri((UriRecord)record); } else if (record instanceof TextRecord) { smartPosterRecord.setTitle((TextRecord)record); } else if (record instanceof ActionRecord) { smartPosterRecord.setAction((ActionRecord)record); } } } return smartPosterRecord; }
private void readFromNFC(Ndef ndef) { try { ndef.connect(); NdefMessage ndefMessage = ndef.getNdefMessage(); String message = new String(ndefMessage.getRecords()[0].getPayload()); Log.d(TAG, "readFromNFC: "+message); mTvMessage.setText(message); ndef.close(); } catch (IOException | FormatException e) { e.printStackTrace(); } }
private void write(String text, Tag tag) throws IOException, FormatException { /* http://stackoverflow.com/questions/11427997/android-app-to-add-mutiple-record-in-nfc-tag */ // We want to include a reference to the app, for those who don't have one. // This way, their phones will open this app when a tag encoded with this app is used. String arrPackageName = "com.briankhuu.nfcmessageboard"; final int AAR_RECORD_BYTE_LENGTH = 50; // I guess i suck at byte counting. well at least this should still work. This approach does lead to wasted space however. //infoMsg = "\n\n---\n To post here. Use the "NFC Messageboard" app: https://play.google.com/store/search?q=NFC%20Message%20Board "; // Trim to size (for now this is just a dumb trimmer...) (Later on, you want to remove whole post first // Seem that header and other things takes 14 chars. For safety. Lets just remove 20. // 0 (via absolute value) < valid entry size < Max Tag size final int NDEF_RECORD_HEADER_SIZE = 6; final int NDEF_STRING_PAYLOAD_HEADER_SIZE = 4; int maxTagByteLength = Math.abs(tag_size - NDEF_RECORD_HEADER_SIZE - NDEF_STRING_PAYLOAD_HEADER_SIZE - AAR_RECORD_BYTE_LENGTH); if (text.length() >= maxTagByteLength ){ // Write like normal if content to write will fit without modification // Else work out what to remove. For now, just do a dumb trimming. // Unicode characters may take more than 1 byte. text = truncateWhenUTF8(text, maxTagByteLength); } // Write tag //NdefRecord[] records = { createRecord(text), aarNdefRecord }; NdefMessage message = new NdefMessage(new NdefRecord[]{ createRecord(text) ,NdefRecord.createApplicationRecord(arrPackageName) }); Ndef ndef = Ndef.get(tag); ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); }
private byte[] readTag(Tag tag) throws IOException, FormatException, ReadingTagException { List<String> tech = Arrays.asList(tag.getTechList()); if (tech.contains(Ndef.class.getName())) { Log.v(TAG, "Read formatted tag."); return readNdeftag(Ndef.get(tag)); } else if (tech.contains(MifareUltralight.class.getName())) { Log.v(TAG, "Read Mifare ultralight tag."); return readMifareUltralight(MifareUltralight.get(tag)); } Toast.makeText(this, "No supported tag found.", Toast.LENGTH_SHORT).show(); Log.e(TAG, "No supported tag found: " + tech); throw new ReadingTagException("No supported tag found."); }
private byte[] readNdeftag(Ndef tag) throws IOException, FormatException, ReadingTagException { NdefMessage message = tag.getNdefMessage(); if (message.getRecords().length == 0) { Toast.makeText(this, "Empty tag found.", Toast.LENGTH_SHORT).show(); throw new ReadingTagException("Empty tag."); } return message.getRecords()[0].getPayload(); }
@Override public void nfcIntentDetected(Intent intent, String action) { Log.d(TAG, "nfcIntentDetected: " + action); Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (messages != null) { NdefMessage[] ndefMessages = new NdefMessage[messages.length]; for (int i = 0; i < messages.length; i++) { ndefMessages[i] = (NdefMessage) messages[i]; } if(ndefMessages.length > 0) { // read as much as possible Message message = new Message(); for (int i = 0; i < messages.length; i++) { NdefMessage ndefMessage = (NdefMessage) messages[i]; for(NdefRecord ndefRecord : ndefMessage.getRecords()) { try { message.add(Record.parse(ndefRecord)); } catch (FormatException e) { // if the record is unsupported or corrupted, keep as unsupported record message.add(UnsupportedRecord.parse(ndefRecord)); } } } readNdefMessage(message); } else { readEmptyNdefMessage(); } } else { readNonNdefMessage(); } }
public static GcActionRecord parseNdefRecord(NdefRecord ndefRecord) throws FormatException { byte[] payload = ndefRecord.getPayload(); if ((payload[0] & GcActionRecord.NUMERIC_CODE) != 0) { return new GcActionRecord(Action.getActionByValue(payload[1])); } else { return new GcActionRecord(Record.parse(payload, 1, payload.length - 1)); } }
public static GenericControlRecord parseNdefRecord(NdefRecord ndefRecord) throws FormatException { byte[] payload = ndefRecord.getPayload(); normalizeMessageBeginEnd(payload, 1, payload.length -1); Message payloadNdefMessage = Message.parseNdefMessage(payload, 1, payload.length - 1); GenericControlRecord genericControlRecord = new GenericControlRecord(); genericControlRecord.setConfigurationByte(payload[0]); for (Record record : payloadNdefMessage) { if (record instanceof GcTargetRecord) { genericControlRecord.setTarget((GcTargetRecord)record); } else if (record instanceof GcActionRecord) { genericControlRecord.setAction((GcActionRecord)record); } else if (record instanceof GcDataRecord) { genericControlRecord.setData((GcDataRecord)record); } else { throw new IllegalArgumentException("Unexpected record " + record.getClass().getName()); } } if (!genericControlRecord.hasTarget()) { throw new IllegalArgumentException("Expected target record"); } return genericControlRecord; }
/** * {@link NdefMessage} constructor. * * @param ndefMessage * @throws FormatException if known record type cannot be parsed */ public Message(NdefMessage ndefMessage) throws FormatException { for(NdefRecord record : ndefMessage.getRecords()) { add(Record.parse(record)); } }
/** * {@link Parcelable} array constructor. If multiple messages, records are added in natural order. * * @param messages {@link NdefMessage}s in {@link Parcelable} array. * @throws FormatException if known record type cannot be parsed */ public Message(Parcelable[] messages) throws FormatException { for (int i = 0; i < messages.length; i++) { NdefMessage message = (NdefMessage) messages[i]; for(NdefRecord record : message.getRecords()) { add(Record.parse(record)); } } }
/** * Parse single record. * * @param record record to parse * @return corresponding {@link Record} subclass - or null if not known * @throws FormatException if known record type cannot be parsed * @throws IllegalArgumentException if zero or more than one record */ protected static Record parse(byte[] record) throws FormatException { NdefMessage message = new NdefMessage(record); if(message.getRecords().length != 1) { throw new IllegalArgumentException("Single record expected"); } return Record.parse(message.getRecords()[0]); }
boolean writeUriCustomHeader(String uri, String technology, byte header, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final Tag mockTag = mTestUtilities.mockTag(technology); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag); NfcWriteUtility nfcWriteUtility = mTestUtilities.determineMockType(null); return nfcWriteUtility != null && (readonly ? nfcWriteUtility.makeOperationReadOnly().writeUriWithPayloadToTagFromIntent(uri, header, intent) : nfcWriteUtility.writeUriWithPayloadToTagFromIntent(uri, header, intent)); }
boolean writeUriCustomHeader(String uri, String technology, byte header, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final Tag mockTag = mTestUtilities.mockTag(technology); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag); NfcWriteUtility nfcWriteUtility = mTestUtilities.determineMockType(technology); return nfcWriteUtility != null && (readonly ? nfcWriteUtility.makeOperationReadOnly().writeUriWithPayloadToTagFromIntent(uri, header, intent) : nfcWriteUtility.writeUriWithPayloadToTagFromIntent(uri, header, intent)); }
/** * {@inheritDoc} */ @Override public boolean writeUriToTagFromIntent(@NotNull String urlAddress, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { NdefMessage ndefMessage = mNfcMessageUtility.createUri(urlAddress); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeUriWithPayloadToTagFromIntent(@NotNull String urlAddress, byte payloadHeader, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { NdefMessage ndefMessage = mNfcMessageUtility.createUri(urlAddress, payloadHeader); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeTelToTagFromIntent(@NotNull String telephone, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { final NdefMessage ndefMessage = mNfcMessageUtility.createTel(telephone); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeSmsToTagFromIntent(@NotNull String number, String message, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { final NdefMessage ndefMessage = mNfcMessageUtility.createSms(number, message); final Tag tag = retrieveTagFromIntent(intent); return mWriteUtility.writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeGeolocationToTagFromIntent(Double latitude, Double longitude, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { final NdefMessage ndefMessage = mNfcMessageUtility.createGeolocation(latitude, longitude); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeEmailToTagFromIntent(@NotNull String recipient, String subject, String message, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException { final NdefMessage ndefMessage = mNfcMessageUtility.createEmail(recipient, subject, message); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeBluetoothAddressToTagFromIntent(@NotNull String macAddress, Intent intent) throws InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final NdefMessage ndefMessage = mNfcMessageUtility.createBluetoothAddress(macAddress); final Tag tag = retrieveTagFromIntent(intent); return writeToTag(ndefMessage, tag); }
/** * {@inheritDoc} */ @Override public boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException { setReadOnly(true); boolean result = writeToNdef(message, ndef); setReadOnly(false); return result; }
/** * {@inheritDoc} * Precondition : Telephone should not be null */ @Override public NdefMessage createTel(@NotNull String telephone) throws FormatException { telephone = telephone.startsWith("+") ? "+" + telephone.replaceAll("\\D", "") : telephone.replaceAll("\\D", ""); if (!PhoneNumberUtils.isGlobalPhoneNumber(telephone)) { throw new FormatException(); } return createUriMessage(telephone, NfcPayloadHeader.TEL); }
private AsyncOperationCallback getSucceedingAsyncOperationCallback() throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException { final Tag mockTag = mTestUtilities.mockTag(TestUtilities.NDEF); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag); return new AsyncOperationCallback() { @Override public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException { return true; } }; }
/** * {@inheritDoc} * Precondition : lat- and longitude, max 6 decimals */ @Override public NdefMessage createGeolocation(Double latitude, Double longitude) throws FormatException { latitude = Math.round(latitude * Math.pow(10, 6)) / Math.pow(10, 6); longitude = Math.round(longitude * Math.pow(10, 6)) / Math.pow(10, 6); String address = "geo:" + latitude.floatValue() + "," + longitude.floatValue(); String externalType = "nfclab.com:geoService"; return createUriMessage(address, NfcPayloadHeader.CUSTOM_SCHEME); }
/** * {@inheritDoc} * Precondition : At least recipient should not be null */ @Override public NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException { subject = (subject != null) ? subject : ""; message = (message != null) ? message : ""; String address = recipient + "?subject=" + subject + "&body=" + message; return createUriMessage(address, NfcPayloadHeader.MAILTO); }
/** * {@inheritDoc} * Precondition : macAddress should not be null */ @Override public NdefMessage createBluetoothAddress(@NotNull String macAddress) throws FormatException { byte[] payload = convertBluetoothToNdefFormat(macAddress); NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, NfcType.BLUETOOTH_AAR, null, payload); return new NdefMessage(record); }
@Override public boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException { Ndef ndef = Ndef.get(tag); NdefFormatable formatable = NdefFormatable.get(tag); boolean result; if (readOnly) { result = writeToNdefAndMakeReadonly(message, ndef) || writeToNdefFormatableAndMakeReadonly(message, formatable); } else { result = writeToNdef(message, ndef) || writeToNdefFormatable(message, formatable); } readOnly = false; return result; }
@Override public void executeWriteOperation(final Intent intent, final Object... args) { if (checkDoubleArguments(args.getClass()) || args.length != 2 || intent == null) { throw new UnsupportedOperationException("Invalid arguments"); } setAsyncOperationCallback(new AsyncOperationCallback() { @Override public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException { return writeUtility.writeGeolocationToTagFromIntent((Double) args[0], (Double) args[1], intent); } }); super.executeWriteOperation(); }
@Override public void executeWriteOperation(final Intent intent, final Object... args) { if (checkStringArguments(args.getClass()) || args.length != 1 || intent == null) { throw new UnsupportedOperationException("Invalid arguments"); } setAsyncOperationCallback(new AsyncOperationCallback() { @Override public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException { return writeUtility.writeTelToTagFromIntent((String) args[0], intent); } }); super.executeWriteOperation(); }
/** * @see be.appfoundry.nfclibrary.utilities.async.AbstractNfcAsync#executeWriteOperation(android.content.Intent, Object...) */ @Override public void executeWriteOperation(final Intent intent, final Object... args) { if (checkStringArguments(args.getClass()) || args.length != 2 || intent == null) { throw new UnsupportedOperationException("Invalid arguments"); } setAsyncOperationCallback(new AsyncOperationCallback() { @Override public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException { return writeUtility.writeSmsToTagFromIntent((String) args[0], (String) args[1], intent); } }); executeWriteOperation(); }
private AsyncOperationCallback getFailingAsyncOperationCallback() { return new AsyncOperationCallback() { @Override public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException { return false; } }; }
boolean writePhoneNumber(String phoneNumber, String technology, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final Tag mockTag = mTestUtilities.mockTag(technology); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG,mockTag); NfcWriteUtility nfcMessageUtility = mTestUtilities.determineMockType(null); return nfcMessageUtility != null && (readonly ? nfcMessageUtility.makeOperationReadOnly().writeTelToTagFromIntent(phoneNumber, intent) : nfcMessageUtility.writeTelToTagFromIntent(phoneNumber, intent)); }
boolean writeUri(String uri, String technology, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final Tag mockTag = mTestUtilities.mockTag(technology); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag); NfcWriteUtility nfcWriteUtility = mTestUtilities.determineMockType(technology); return writeUriCustomHeader(uri,technology,NfcPayloadHeader.HTTP_WWW,false); }
boolean writeGeoLocation(Double latitude, Double longitude, String technology, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException { final Tag mockTag = mTestUtilities.mockTag(technology); final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag); NfcWriteUtility nfcMessageUtility = mTestUtilities.determineMockType(null); return (readonly ? nfcMessageUtility.makeOperationReadOnly().writeGeolocationToTagFromIntent(latitude, longitude, intent) : nfcMessageUtility.writeGeolocationToTagFromIntent(latitude, longitude, intent)); }