IOException 向 NFC 卡写入数据

IOException writing data to NFC card

我正在尝试使用 Android 应用程序将数据写入 NFC 卡,但是当我尝试写入数据时,我得到了 java.io.IOExcetion。日志告诉我它是空的。我添加了 printstacktrace,它指向 android.nfc.tech.NdefFormatble.format(NdefFormarmatable.java:131) 和 android.nfc.tech.NdefFormatble.format(NdefFormarmatable.java:94) 处的错误。我查看了这个 class 以了解错误是什么,Android Studio 说它无法解析 class 中某些导入的符号。我不知道出了什么问题,如果能帮助解决这个问题,我将不胜感激。我之前确实有过这个工作,然后突然间我开始收到这个错误。我确实将 Android Studio 更新到 3.1.1,但我尝试使用 AS 3.0 和 2.3,但我得到了同样的错误。我已经包含了所有被调用的方法以及堆栈跟踪。

这是卡被格式化并写入的地方:

    private void formatTag(Tag tag, NdefMessage ndefMessage) {
    try {

        NdefFormatable ndefFormatable = NdefFormatable.get(tag);

        if (ndefFormatable == null) {
            Toast.makeText(this, "Tag is not ndef formatable!", Toast.LENGTH_SHORT).show();
            return;
        }


        ndefFormatable.connect();
        ndefFormatable.format(ndefMessage);   ***<----MainActivity.java:469***
        ndefFormatable.close();

        Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        Log.e("formatTag", "" + e.getMessage());
        e.printStackTrace();
    }

}

这是写NDEF报文的方法

    private void writeNdefMessage(Tag tag, NdefMessage ndefMessage) {

    try {

        if (tag == null) {
            Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
            return;
        }

        Ndef ndef = Ndef.get(tag);

        if (ndef == null) {
            // format tag with the ndef format and writes the message.
            formatTag(tag, ndefMessage);      **<----- MainActivity.java 494**
        } else {
            ndef.connect();

            if (!ndef.isWritable()) {
                Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();

                ndef.close();
                return;
            }

            ndef.writeNdefMessage(ndefMessage);
            ndef.close();

            Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();

        }

    } catch (Exception e) {
        Log.e("writeNdefMessage", "" + e.getMessage());
        e.printStackTrace();
    }

这是调用 writeNdefMessage 的地方

    @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
        Toast.makeText(this, "NfcIntent!", Toast.LENGTH_SHORT).show();

        if(tglReadWrite.isChecked())
        {
            Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            if(parcelables != null && parcelables.length > 0)
            {
                readDataFromMessage((NdefMessage) parcelables[0]);
            }else{
                Toast.makeText(this, "No NDEF messages found!", Toast.LENGTH_SHORT).show();
            }

        }else{
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            NdefMessage ndefMessage = createNdefMessage(mToken.getText()+";");


            writeNdefMessage(tag, ndefMessage);    ***<---- MainActivity.java:406***
        }

    }
}

这里是 StackTrace

    04-13 02:50:51.112 6311-6311/com.appsolutedevelopment.labourstaff E/formatTag: null

04-13 02:50:51.112 6311-6311/com.appsolutedevelopment.labourstaff W/System.错误:java.io.IOException 04-13 02:50:51.113 6311-6311/com.appsolutedevelopment.labourstaff W/System.err: 在 android.nfc.tech.NdefFormatable.format(NdefFormatable.java:131) 在 android.nfc.tech.NdefFormatable.format(NdefFormatable.java:94) 在 com.appsolutedevelopment.labourstaff.MainActivity.formatTag(MainActivity.java:469) 在 com.appsolutedevelopment.labourstaff.MainActivity.writeNdefMessage(MainActivity.java:494) 在 com.appsolutedevelopment.labourstaff.MainActivity.onNewIntent(MainActivity.java:406) 在 android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1228) 在 android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1240) 在 android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2946) 在 android.app.ActivityThread.performNewIntents(ActivityThread.java:2958) 在 android.app.ActivityThread.handleNewIntent(ActivityThread.java:2967) 在 android.app.ActivityThread.-wrap15(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1648) 在 android.os.Handler.dispatchMessage(Handler.java:105) 在 android.os.Looper.loop(Looper.java:156) 在 android.app.ActivityThread.main(ActivityThread.java:6523) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

最后是 NdefFormatable class

package android.nfc.tech;

import android.nfc.ErrorCodes;      ***<---- Cannot resolve symbol 'ErrorCodes'***
import android.nfc.FormatException;
import android.nfc.INfcTag;     ***<---- Cannot resolve symbol 'INfcTag'***
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.os.RemoteException;
import android.util.Log;

import java.io.IOException;

/**
 * Provide access to NDEF format operations on a {@link Tag}.
 *
 * <p>Acquire a {@link NdefFormatable} object using {@link #get}.
 *
 * <p>Android devices with NFC must only enumerate and implement this
 * class for tags for which it can format to NDEF.
 *
 * <p>Unfortunately the procedures to convert unformated tags to NDEF formatted
 * tags are not specified by NFC Forum, and are not generally well-known. So
 * there is no mandatory set of tags for which all Android devices with NFC
 * must support {@link NdefFormatable}.
 *
 * <p class="note"><strong>Note:</strong> Methods that perform I/O operations
 * require the {@link android.Manifest.permission#NFC} permission.
 */
public final class NdefFormatable extends BasicTagTechnology {
    private static final String TAG = "NFC";

    /**
     * Get an instance of {@link NdefFormatable} for the given tag.
     * <p>Does not cause any RF activity and does not block.
     * <p>Returns null if {@link NdefFormatable} was not enumerated in {@link Tag#getTechList}.
     * This indicates the tag is not NDEF formatable by this Android device.
     *
     * @param tag an NDEF formatable tag
     * @return NDEF formatable object
     */
    public static NdefFormatable get(Tag tag) {
        if (!tag.hasTech(TagTechnology.NDEF_FORMATABLE)) return null;
        try {
            return new NdefFormatable(tag);
        } catch (RemoteException e) {
            return null;
        }
    }

    /**
     * Internal constructor, to be used by NfcAdapter
     * @hide
     */
    public NdefFormatable(Tag tag) throws RemoteException {
        super(tag, TagTechnology.NDEF_FORMATABLE);
    }

    /**
     * Format a tag as NDEF, and write a {@link NdefMessage}.
     *
     * <p>This is a multi-step process, an IOException is thrown
     * if any one step fails.
     * <p>The card is left in a read-write state after this operation.
     *
     * <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 firstMessage the NDEF message to write after formatting, 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 to write is malformed
     */
    public void format(NdefMessage firstMessage) throws IOException, FormatException {
        format(firstMessage, false);    ***<----NdefFormatable.java:94***
    }

    /**
     * Formats a tag as NDEF, write a {@link NdefMessage}, and make read-only.
     *
     * <p>This is a multi-step process, an IOException is thrown
     * if any one step fails.
     * <p>The card is left in a read-only state if this method returns successfully.
     *
     * <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 firstMessage the NDEF message to write after formatting
     * @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 formatReadOnly(NdefMessage firstMessage) throws IOException, FormatException {
        format(firstMessage, true);
    }

    /*package*/ void format(NdefMessage firstMessage, boolean makeReadOnly) throws IOException,
            FormatException {
        checkConnected();

        try {
            int serviceHandle = mTag.getServiceHandle();
            INfcTag tagService = mTag.getTagService();
            int errorCode = tagService.formatNdef(serviceHandle, MifareClassic.KEY_DEFAULT);
            switch (errorCode) {
                case ErrorCodes.SUCCESS:
                    break;
                case ErrorCodes.ERROR_IO:
                    throw new IOException();     ***<---- NdefFormatable.java:131***
                case ErrorCodes.ERROR_INVALID_PARAM:
                    throw new FormatException();
                default:
                    // Should not happen
                    throw new IOException();
            }
            // Now check and see if the format worked
            if (!tagService.isNdef(serviceHandle)) {
                throw new IOException();
            }

            // Write a message, if one was provided
            if (firstMessage != null) {
                errorCode = tagService.ndefWrite(serviceHandle, firstMessage);
                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();
                }
            }

            // optionally make read-only
            if (makeReadOnly) {
                errorCode = tagService.ndefMakeReadOnly(serviceHandle);
                switch (errorCode) {
                    case ErrorCodes.SUCCESS:
                        break;
                    case ErrorCodes.ERROR_IO:
                        throw new IOException();
                    case ErrorCodes.ERROR_INVALID_PARAM:
                        throw new IOException();
                    default:
                        // Should not happen
                        throw new IOException();
                }
            }
        } catch (RemoteException e) {
            Log.e(TAG, "NFC service dead", e);
        }
    }
}

如果我遗漏了什么或有人需要更多信息,请提出来,我会提供所需的一切。如果有人能阐明这一点,我将不胜感激,因为它已经让我纠结了这么久。

谢谢。

我在这里找到了这个问题的答案 . This explains what is going on in my app when I try to write to the NFC card after an unsuccessful write operation. If anyone is looking for a solution to this problem then this 可能会有一些帮助。如果您正在努力实现向 NFC tokens/cards 读取和写入关键数据,那么我建议使用 nfcA 而不是 NDEF。