chariotsolutions / phonegap-nfc

PhoneGap NFC Plugin
MIT License
706 stars 555 forks source link

Android: NFC can lock up in addNdefFormatableListener after a write #382

Closed kenwalker closed 4 years ago

kenwalker commented 4 years ago

This may be user error since I cannot find an example of how to transform NdefFormatable tags into Ndef tags.

I modified the provided Ionic read example to listen instead for addNdefFormatableListener and in that callback wrote a record out to turn it into an Ndef format tag. This first sequence is successful. That NFC tag will be Ndef and will have the correct record.

Repeat these steps with another NFC tag that is NdefFormatabe, you get a beep but no callback. In the code snippet below, no In callback alert will be fired the second time, and NFC is now no longer working on the device. Other tools, such as "NFC Tools" will no longer work. You have to turn off NFC, wait, then turn it back on. So perhaps there's user error by me in what can be done in this callback and this is not the correct way to change it to Ndef format.

It was easy to return an Ndef tag to an NdefFormatable one again by using the Format memory option in the NFC Tools Android application.

Thanks for the library, it's been great for my Live Action Roleplaying sign-in application on iOS and Android.

phonegap-nfc 1.0.4 "NFC"

        $ionicPlatform.ready(function() {
            nfc.addNdefFormatableListener(function (nfcEvent) {
              alert('In callback ' );
              console.log(JSON.stringify(nfcEvent.tag, null, 4));
              $rootScope.$apply(function(){
                  angular.copy(nfcEvent.tag, tag);
                  // if necessary $state.go('some-route')
              });
              var message = [
                ndef.uriRecord("https://google.com")
              ];
              nfc.write(message, function(ok) {
                alert('Write ok' );
              }, function(error) {
                alert('Write error ' + JSON.stringify(message));
              });
        }, function () {
              console.log("Listening for NdefFormatable Tags.");
          }, function (reason) {
              alert("Error adding NFC Listener " + reason);
          });

        });
don commented 4 years ago

With Android you need to have multiple listeners to do this. Use both addNdefListener and addNdefFormattableListener. Android will call the most specific listener for the tag. It's also ok to use one function to handle events from both callbacks.

FWIW the listener functions don't work well with the Ionic wrappers since the error can be called multiple times. IMO you're much better off using the callbacks directly for this.

You might be able to do everything using readerMode with one observable. I'll be adding wrappers for readerMode to Ionic soon.

kenwalker commented 4 years ago

Thanks @don