【问题标题】:Android write ID to an empty NFC tagAndroid 将 ID 写入空的 NFC 标签
【发布时间】:2016-07-30 04:01:06
【问题描述】:

我制作了一个可以读取 NFC 标签的应用,但我面临的问题是并非所有频段都有 ID。

是否可以为空标签分配新的 ID?

private String tagInfoId = "";
private NfcAdapter nfcAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_player);
    if (!userPrefs.isLoggedIn().get()) finish();
    trackerService = ServiceGateway.createAuthorizedService(TrackerService.class);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter == null) {
        Toast.makeText(this,
                "NFC NOT supported on this devices!",
                Toast.LENGTH_LONG).show();
        finish();
    } else if (!nfcAdapter.isEnabled()) {
        Toast.makeText(this,
                "NFC NOT Enabled!",
                Toast.LENGTH_LONG).show();
        finish();
    }
}

@Override
protected void onResume() {
    super.onResume();

    Intent intent = getIntent();
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag == null) {
            Log.d(TAG, "tag == null");

            //here is possible to write a new tag code ???

        } else {
            byte[] tagId = tag.getId();
            for (int i = 0; i < tagId.length; i++) {
                tagInfoId += Integer.toHexString(tagId[i] & 0xFF);
            }
            Log.d(TAG, "onResume() called with: " + "tagID:" + tagInfoId);

        }
    }
}

Manifest.xml

   <activity
            android:name=".activities.NfcActivity"
            android:noHistory="true"
            android:theme="@android:style/Theme.Translucent.NoTitleBar">
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

另外,如果我为一个新标签分配一个 ID,它会以相同的方式读取它还是我必须更改上面的代码?

【问题讨论】:

    标签: android tags nfc


    【解决方案1】:

    对于 NFC 意图,意图的额外 TAG 绝不应为空(或 null)。因此,您应该始终从intent.getParcelableExtra(NfcAdapter.EXTRA_TAG) 获取Tag 对象,并且您永远不应该分支到if (tag == null) {

    如果您仍然到达tag == null 分支,那么这与没有标识符的标签无关。相反,这意味着您设备的 NFC 堆栈中出现了严重错误。例如,这可能是标签读取在很早的阶段被中断,或者标签没有正确说出阅读器期望的协议。由于您没有收到Tag 对象,因此也无法与标签进行通信。

    因此,您对此无能为力。您只能尝试重新读取标签(通过手机重新点击)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多