简体   繁体   中英

How to do multiple NFC-tag writes in Android

How should we go about writing to multiple NFC tags in, for example, a loop. We have an array of data that should be written to different tags on startup of the Android application.

We get notified in onNewIntent() when a new NFC tag is within range, but we would like to have a method where we have a loop that goes something like this...

for(all elements) {
    writeInfoToTag();
}

But that's not possible to call without there actually being a NFC tag withing range, and the program can't wait for a NFC tag without crashing.

We have methods for reading and writing to an NFC tag, but at this point all of the methods that interacts with the tags needs to be called from onNewIntent() .

Any ideas on how to do this?

You can achieve this using this pseudo code.

private static int elementNo = 0;

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if(elementNo<elements.size()){
        writeElementToTag(elements.get(elementNo));
        elementNo++;
    }
}

If element size is n then you have to touch n tags one by one. There is no way to write all tag once using android.

While the underlying hardware would usually support to handle multiple tags concurrently, the current Android NFC API only allows one tag at a time. Thus, waiting for all tags to become present and then writing data to all of them is simply not possible on current Android devices.

Moreover, consider the discovery of an NFC tag as a form of user interaction (ie the user (intentionally) places an NFC tag on the NFC reader). Thus, a typical program flow would not be that your app is started and immediately writes to a tag, but instead that

  • your app is started,
  • "waits" for a tag (actually: registers to be notified upon tag discovery), and
  • upon tag discovery, writes to that tag.

Hence, your interaction (read/write) with the tag starts in onNewIntent (or whichever method is invoked to notify your activity that there is a new tag present). There, you can then decide which dataset you want to write to that specific tag (eg by using a counter, by matching the tag ID against a database, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM