android.nfc.TagLostException Java Examples

The following examples show how to use android.nfc.TagLostException. 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: Ndef.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Read the current {@link android.nfc.NdefMessage} on this tag.
 *
 * <p>This always reads the current NDEF Message stored on the tag.
 *
 * <p>Note that this method may return null if the tag was in the
 * INITIALIZED state as defined by NFC Forum, as in that state the
 * tag is formatted to support NDEF but does not contain a message yet.
 *
 * <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.
 *
 * @return the NDEF Message, can 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 on the tag is malformed
 */
public NdefMessage getNdefMessage() 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)) {
            NdefMessage msg = tagService.ndefRead(serviceHandle);
            if (msg == null && !tagService.isPresent(serviceHandle)) {
                throw new TagLostException();
            }
            return msg;
        } else if (!tagService.isPresent(serviceHandle)) {
            throw new TagLostException();
        } else {
            return null;
        }
    } catch (RemoteException e) {
        Log.e(TAG, "NFC service dead", e);
        return null;
    }
}
 
Example #2
Source File: PaymentReaderXcvr.java    From smartcard-reader with GNU General Public License v3.0 6 votes vote down vote up
private boolean selectPpse() throws TagLostException, IOException {
    Log.d(TAG, "select PPSE");
    CommandApdu selectPpseApdu = new SelectApdu(mPpseAidBytes);
    selectPpseApdu.setCommandName("select ppse");
    ResponseApdu rspApdu = sendAndRcv(selectPpseApdu, true);

    if (rspApdu.isStatus(SW_NO_ERROR)) {
        mUiCallbacks.onOkay(mContext.getString(R.string.select_ppse_ok,
                rspApdu.getSW1SW2()));
    } else {
        mUiCallbacks.onError(
                mContext.getString(R.string.select_ppse_err,
                        rspApdu.getSW1SW2(),
                        ApduParser.parse(false, rspApdu.toBytes())));
        return false;
    }
    try {
        mPpseDdf = parseFCIDDF(rspApdu.getData());
    } catch (TLVException e) {
        mPpseDdf = null;
        mUiCallbacks.onError(e.getMessage());
        return true;
    }
    return true;
}
 
Example #3
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Connects to NFC tag.
 */
public void connect() throws IOException, TagLostException {
    if (!mTech.isConnected()) {
        mTech.connect();
        mWasConnected = true;
    }
}
 
Example #4
Source File: MainActivity.java    From bankomatinfos with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(Void... params) {
	AppController ctl = AppController.getInstance();
	ctl.clearLog();
	try {
		ctl.log(getResources().getString(R.string.app_name)
				+ " version " + getAppVersion(MainActivity.this));
		NfcBankomatCardReader reader = new NfcBankomatCardReader(
				nfcTag, MainActivity.this);
		reader.connectIsoDep();
		// read setting value
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);
		_cardReadingResults = reader.readAllCardData(prefs.getBoolean(
				"perform_full_file_scan", false));
		ctl.setCardInfo(_cardReadingResults);
		reader.disconnectIsoDep();
	} catch (NoSmartCardException nsce) {
		Log.w(TAG,
				"Catched NoSmartCardException during reading the card",
				nsce);
		error = ERROR_NO_SMARTCARD;
		return false;
	} catch (TagLostException tle) {
		Log.w(TAG, "Catched TagLostException during reading the card",
				tle);
		error = ERROR_TAG_LOST;
		return false;
	} catch (IOException e) {
		Log.e(TAG, "Catched IOException during reading the card", e);
		error = ERROR_IO_EX;
		ctl.log("-----------------------------------------------");
		ctl.log("ERROR ERROR ERROR:");
		ctl.log("Catched IOException during reading the card:");
		ctl.log(getStacktrace(e));
		ctl.log("-----------------------------------------------");
		return false;
	}
	return true;
}
 
Example #5
Source File: TransceiveResult.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
public byte[] getResponseOrThrow() throws IOException {
    switch (mResult) {
        case RESULT_SUCCESS:
            return mResponseData;
        case RESULT_TAGLOST:
            throw new TagLostException("Tag was lost.");
        case RESULT_EXCEEDED_LENGTH:
            throw new IOException("Transceive length exceeds supported maximum");
        default:
            throw new IOException("Transceive failed");
    }
}
 
Example #6
Source File: NdefImpl.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
/**
 * Read the current {@link android.nfc.NdefMessage} on this tag.
 *
 * <p>This always reads the current NDEF Message stored on the tag.
 *
 * <p>Note that this method may return null if the tag was in the
 * INITIALIZED state as defined by NFC Forum, as in that state the
 * tag is formatted to support NDEF but does not contain a message yet.
 *
 * <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.
 *
 * @return the NDEF Message, can 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 on the tag is malformed
 */
@Override
public NdefMessage getNdefMessage() 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)) {
            NdefMessage msg = tagService.ndefRead(serviceHandle);
            if (msg == null && !tagService.isPresent(serviceHandle)) {
                throw new TagLostException();
            }
            return msg;
        } else if (!tagService.isPresent(serviceHandle)) {
            throw new TagLostException();
        } else {
            return null;
        }
    } catch (RemoteException e) {
        Log.e(TAG, "NFC service dead", e);
        return null;
    }
}
 
Example #7
Source File: PaymentReaderXcvr.java    From smartcard-reader with GNU General Public License v3.0 5 votes vote down vote up
private boolean selectApp(String aid, EMVApp app) throws TagLostException, IOException {
    Log.d(TAG, "select app: " + aid);
    byte[] aidBytes = Util.hexToBytes(aid);
    ResponseApdu rspApdu = sendAndRcv(new SelectApdu(aidBytes), true);
    
    if (rspApdu.isStatus(SW_NO_ERROR)) {
        mUiCallbacks.onOkay(mContext.getString(R.string.select_app_ok,
                rspApdu.getSW1SW2()));
        if (app != null) {
            try {
                parseFCIADF(rspApdu.getData(), app);
            } catch (Exception e) {
                mUiCallbacks.onError(e.getMessage());
            }
        }
    } else {
        if (rspApdu.getSW1SW2() == SW_SELECTED_FILE_INVALIDATED) {
            Log.d(TAG, "Application blocked!");
        }
        mUiCallbacks.onError(
                mContext.getString(R.string.select_app_err,
                        rspApdu.getSW1SW2(),
                        ApduParser.parse(false, rspApdu.toBytes())));
        return false;
    }        
    return true;
}
 
Example #8
Source File: ReaderXcvr.java    From smartcard-reader with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseApdu sendAndRcv(CommandApdu cmdApdu, boolean ascii)
        throws TagLostException, IOException {
    byte[] cmdBytes = cmdApdu.toBytes();
    String cmdStr = CommandApdu.toString(cmdBytes, cmdApdu.getLc());
    mUiCallbacks.onMessageSend(cmdStr, cmdApdu.getCommandName());
    byte[] rsp = mIsoDep.transceive(cmdBytes);
    ResponseApdu rspApdu = new ResponseApdu(rsp);
    byte[] data = rspApdu.getData();

    String parsed = null;
    String errMsg = "no error";
    try {
        if (data.length > 0) {
            parsed = TLVUtil.prettyPrintAPDUResponse(data);
        }
    } catch (TLVException e) {
        parsed = null;
        errMsg = e.getMessage();
    }

    mUiCallbacks.onMessageRcv(bytesToHexAndAscii(rsp, ascii), cmdApdu.getCommandName(), parsed);

    if (data.length > 0 && parsed == null) {
        mUiCallbacks.onError(errMsg);
    }

    /*
    Log.d(TAG, "response APDU: " + Util.bytesToHex(rsp));
    if (data.length > 0) {
        Log.d(TAG, TLVUtil.prettyPrintAPDUResponse(data));
    }
    */
    return rspApdu;
}
 
Example #9
Source File: MCReader.java    From MifareClassicTool with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Read as much as possible from the tag with the given key information.
 * @param keyMap Keys (A and B) mapped to a sector.
 * See {@link #buildNextKeyMapPart()}.
 * @return A Key-Value Pair. Keys are the sector numbers, values
 * are the tag data. This tag data (values) are arrays containing
 * one block per field (index 0-3 or 0-15).
 * If a block is "null" it means that the block couldn't be
 * read with the given key information.<br />
 * On Error, "null" will be returned (tag was removed during reading or
 * keyMap is null). If none of the keys in the key map are valid for reading
 * (and therefore no sector is read), an empty set (SparseArray.size() == 0)
 * will be returned.
 * @see #buildNextKeyMapPart()
 */
public SparseArray<String[]> readAsMuchAsPossible(
        SparseArray<byte[][]> keyMap) {
    SparseArray<String[]> resultSparseArray;
    if (keyMap != null && keyMap.size() > 0) {
        resultSparseArray = new SparseArray<>(keyMap.size());
        // For all entries in map do:
        for (int i = 0; i < keyMap.size(); i++) {
            String[][] results = new String[2][];
            try {
                if (keyMap.valueAt(i)[0] != null) {
                    // Read with key A.
                    results[0] = readSector(
                            keyMap.keyAt(i), keyMap.valueAt(i)[0], false);
                }
                if (keyMap.valueAt(i)[1] != null) {
                    // Read with key B.
                    results[1] = readSector(
                            keyMap.keyAt(i), keyMap.valueAt(i)[1], true);
                }
            } catch (TagLostException e) {
                return null;
            }
            // Merge results.
            if (results[0] != null || results[1] != null) {
                resultSparseArray.put(keyMap.keyAt(i), mergeSectorData(
                        results[0], results[1]));
            }
        }
        return resultSparseArray;
    }
    return null;
}
 
Example #10
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public void write(NdefMessage message)
throws IOException, TagLostException, FormatException, IllegalStateException;
 
Example #11
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public NdefMessage read()
throws IOException, TagLostException, FormatException, IllegalStateException;
 
Example #12
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public void write(NdefMessage message)
        throws IOException, TagLostException, FormatException, IllegalStateException {
    mNdef.writeNdefMessage(message);
}
 
Example #13
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public NdefMessage read()
        throws IOException, TagLostException, FormatException, IllegalStateException {
    return mNdef.getNdefMessage();
}
 
Example #14
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public void write(NdefMessage message)
        throws IOException, TagLostException, FormatException, IllegalStateException {
    mNdefFormattable.format(message);
}
 
Example #15
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Writes NdefMessage to NFC tag.
 */
public void write(NdefMessage message)
        throws IOException, TagLostException, FormatException, IllegalStateException {
    mTechHandler.write(message);
}
 
Example #16
Source File: NfcTagHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public NdefMessage read()
        throws IOException, TagLostException, FormatException, IllegalStateException {
    return mTechHandler.read();
}