android.nfc.FormatException Java Examples

The following examples show how to use android.nfc.FormatException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractFailsTestsAsync.java    From android-nfc-lib with MIT License 6 votes vote down vote up
protected void performAsyncTaskWithReturnValue(AsyncUiCallback asyncUiCallback, NfcWriteUtility nfcWriteUtility, final boolean returnValue) throws InterruptedException {
    mSemaphore = new Semaphore(0);

    this.mAsyncNfcWriteOperation = new WriteEmailNfcAsync(asyncUiCallback,
            new AsyncOperationCallback() {
                @Override
                public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException {
                    return returnValue;
                }
            }
            ,
            nfcWriteUtility
    );

    mHandlerThread.start();
    mSemaphore.acquire();
}
 
Example #2
Source File: NdefAdapter.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
@Override
public NdefMessage ndefRead() throws RemoteException {
    try {
        Message message = operations.readNdefMessage();

        return message.getNdefMessage();
    } catch (FormatException e) {
        Log.d(TAG, "Problem calling ndefRead()", e);
        throw new RemoteException();
    }
}
 
Example #3
Source File: WriteEmailSucceedsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
public void testWriteEmailNdefFormatable() throws IllegalAccessException, FormatException, ClassNotFoundException, ReadOnlyTagException, InsufficientCapacityException, NoSuchFieldException, TagNotPresentException {
    String email = "[email protected]";
    assertTrue(writeEmailToTag(email, TestUtilities.NDEF_FORMATABLE, false));

    assertTrue(mTestUtilities.checkResult(email));
    assertTrue(mTestUtilities.checkPayloadHeader(NfcPayloadHeader.MAILTO));
}
 
Example #4
Source File: NdefWriteImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException {
    setReadOnly(true);
    boolean result = writeToNdef(message, ndef);
    setReadOnly(false);
    return result;
}
 
Example #5
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Precondition :  At least number should not be null
 */
@Override
public NdefMessage createSms(@NotNull String number, String message) throws FormatException {
    number = number.startsWith("+") ? "+" + number.replaceAll("\\D", "") : number.replaceAll("\\D", "");
    if (!PhoneNumberUtils.isGlobalPhoneNumber((number))) {
        throw new FormatException();
    }
    String smsPattern = "sms:" + number + "?body=" + message;
    //String externalType = "nfclab.com:smsService";
    return createUriMessage(smsPattern, NfcPayloadHeader.CUSTOM_SCHEME);
}
 
Example #6
Source File: WriteBluetoothNfcAsync.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * @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();
}
 
Example #7
Source File: WriteUriSucceedsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
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);
}
 
Example #8
Source File: WriteUriNfcAsync.java    From android-nfc-lib with MIT License 5 votes vote down vote up
@Override
public void executeWriteOperation(final Intent intent, final Object... args) {
    if (!checkStringArguments(args.getClass()) || args.length != 1 || !args[0].equals("")){
        throw new UnsupportedOperationException("Invalid arguments!");
    }

    setAsyncOperationCallback(new AsyncOperationCallback() {
        @Override
        public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException {
            return writeUtility.writeUriToTagFromIntent((String) args[0],intent);
        }
    });

    super.executeWriteOperation();
}
 
Example #9
Source File: WriteGeoLocationNfcAsync.java    From android-nfc-lib with MIT License 5 votes vote down vote up
@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();
}
 
Example #10
Source File: NfcWriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #11
Source File: OtpParser.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Parses nfc tag and extracts otp credential from it
 * @param tag an NDEF compatible tag
 * @return OTP data
 * @throws ParseTagException if tag has no NDEF Tag Technology or there is no YK OTP payload
 */
public static @NonNull String parseTag(Tag tag) throws ParseTagException {
    Ndef ndef = Ndef.get(tag);
    if (ndef == null) {
        throw new ParseTagException("Tag is not NDEF formatted");
    }
    NdefMessage message;
    try {
        ndef.connect();
        message = ndef.getNdefMessage();
    } catch (FormatException | IOException e) {
        message = ndef.getCachedNdefMessage();
    } finally {
        try {
            ndef.close();
        } catch (IOException ignore) {
        }
    }

    if (message == null) {
        throw new ParseTagException("Couldn't read ndef message");
    }

    String parsedData = parseNdefMessage(message);
    if (parsedData != null) {
        return parsedData;
    }
    throw new ParseTagException("Tag doesn't have YK OTP payload");
}
 
Example #12
Source File: GenericTaskTestsAsync.java    From android-nfc-lib with MIT License 5 votes vote down vote up
private AsyncOperationCallback getFailingAsyncOperationCallback() {
    return new AsyncOperationCallback() {
        @Override
        public boolean performWrite(NfcWriteUtility writeUtility) throws ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException, FormatException {
            return false;
        }
    };
}
 
Example #13
Source File: Ndef.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Overwrite the {@link NdefMessage} on this tag.
 *
 * <p>This is an I/O operation and will block until complete. It must
 * not be called from the main application thread. A blocked call will be canceled with
 * {@link IOException} if {@link #close} is called from another thread.
 *
 * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
 *
 * @param msg the NDEF Message to write, must not be null
 * @throws TagLostException if the tag leaves the field
 * @throws IOException if there is an I/O failure, or the operation is canceled
 * @throws FormatException if the NDEF Message to write is malformed
 */
public void writeNdefMessage(NdefMessage msg) throws IOException, FormatException {
    checkConnected();

    try {
        INfcTag tagService = mTag.getTagService();
        if (tagService == null) {
            throw new IOException("Mock tags don't support this operation.");
        }
        int serviceHandle = mTag.getServiceHandle();
        if (tagService.isNdef(serviceHandle)) {
            int errorCode = tagService.ndefWrite(serviceHandle, msg);
            switch (errorCode) {
                case ErrorCodes.SUCCESS:
                    break;
                case ErrorCodes.ERROR_IO:
                    throw new IOException();
                case ErrorCodes.ERROR_INVALID_PARAM:
                    throw new FormatException();
                default:
                    // Should not happen
                    throw new IOException();
            }
        }
        else {
            throw new IOException("Tag is not ndef");
        }
    } catch (RemoteException e) {
        Log.e(TAG, "NFC service dead", e);
    }
}
 
Example #14
Source File: NfcWriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #15
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #16
Source File: NdefImpl.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
/**
 * Overwrite the {@link NdefMessage} on this tag.
 *
 * <p>This is an I/O operation and will block until complete. It must
 * not be called from the main application thread. A blocked call will be canceled with
 * {@link IOException} if {@link #close} is called from another thread.
 *
 * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
 *
 * @param msg the NDEF Message to write, must not be null
 * @throws TagLostException if the tag leaves the field
 * @throws IOException if there is an I/O failure, or the operation is canceled
 * @throws FormatException if the NDEF Message to write is malformed
 */
@Override
public void writeNdefMessage(NdefMessage msg) throws IOException, FormatException {
    delegate.checkConnected();

    try {
        INfcTag tagService = delegate.getTag().getTagService();
        if (tagService == null) {
            throw new IOException("Mock tags don't support this operation.");
        }
        int serviceHandle = delegate.getTag().getServiceHandle();
        if (tagService.isNdef(serviceHandle)) {
            int errorCode = tagService.ndefWrite(serviceHandle, msg);
            switch (errorCode) {
                case ErrorCodes.SUCCESS:
                    break;
                case ErrorCodes.ERROR_IO:
                    throw new IOException();
                case ErrorCodes.ERROR_INVALID_PARAM:
                    throw new FormatException();
                default:
                    // Should not happen
                    throw new IOException();
            }
        }
        else {
            throw new IOException("Tag is not ndef");
        }
    } catch (RemoteException e) {
        Log.e(TAG, "NFC service dead", e);
    }
}
 
Example #17
Source File: WriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
@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;
}
 
Example #18
Source File: GenericTaskTestsAsync.java    From android-nfc-lib with MIT License 5 votes vote down vote up
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;
        }
    };
}
 
Example #19
Source File: WriteUriFailsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
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);
}
 
Example #20
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #21
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #22
Source File: WritePhoneSucceedsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
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(technology);

    return nfcMessageUtility != null && (readonly ? nfcMessageUtility.makeOperationReadOnly().writeTelToTagFromIntent(phoneNumber, intent) : nfcMessageUtility.writeTelToTagFromIntent(phoneNumber, intent));
}
 
Example #23
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@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);
}
 
Example #24
Source File: Type2NdefOperations.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
@Override
public Message readNdefMessage() throws FormatException {
	assertFormatted();
	if (lastReadRecords != null) {
		return lastReadRecords;
	}
	else {
		TypeLengthValueReader reader = new TypeLengthValueReader(new TagInputStream(memoryLayout, readerWriter));
		convertRecords(reader);
		return lastReadRecords;
	}
}
 
Example #25
Source File: AbstractNdefOperations.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasNdefMessage() throws FormatException {
	if (lastReadRecords != null && !lastReadRecords.isEmpty())
		return true;

	Collection<Record> ndefMessage = readNdefMessage();
	return !ndefMessage.isEmpty();
}
 
Example #26
Source File: WriteGeolocationFailsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
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));
}
 
Example #27
Source File: WriteEmailSucceedsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
public void testWriteEmailNdef() throws IllegalAccessException, FormatException, ClassNotFoundException, ReadOnlyTagException, InsufficientCapacityException, NoSuchFieldException, TagNotPresentException {
    String email = "[email protected]";
    assertTrue(writeEmailToTag(email, TestUtilities.NDEF, false));

    assertTrue(mTestUtilities.checkResult(email));
    assertTrue(mTestUtilities.checkPayloadHeader(NfcPayloadHeader.MAILTO));
}
 
Example #28
Source File: NdefWriteImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException {
    setReadOnly(true);
    boolean result = writeToNdefFormatable(message, ndefFormat);
    setReadOnly(false);

    return result;

}
 
Example #29
Source File: WriteUtilityImpl.java    From android-nfc-lib with MIT License 4 votes vote down vote up
@Override
public boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException {
    return mNdefWrite.writeToNdefAndMakeReadonly(message, ndef);
}
 
Example #30
Source File: WriteGeolocationFailsTests.java    From android-nfc-lib with MIT License 4 votes vote down vote up
public void testWriteGeoLocationReadOnlyNdefFormatable() throws IllegalAccessException, FormatException, ClassNotFoundException, ReadOnlyTagException, InsufficientCapacityException, NoSuchFieldException, TagNotPresentException {
    double latitude = 0, longitude = 0;
    final String ndefFormatable = TestUtilities.NDEF_FORMATABLE;
    performWriteAndChecks(latitude, longitude, ndefFormatable, true);
}