chariotsolutions / phonegap-nfc

PhoneGap NFC Plugin
MIT License
712 stars 570 forks source link

see if nfc.addMimeTypeListener can be called multiple times #72

Closed don closed 10 years ago

don commented 11 years ago

nfc.addMimeTypeListener("text/foo"); nfc.addMimeTypeListener("text/bar");

floutchito commented 10 years ago

Hello,

As I was testing this possibility, I think I found the answer : NO.

Consider these listeners :

nfc.addMimeTypeListener(
    'app/bt',
    app.firstCallback,
    function() {
        console.log( "Listening for NDEF mime tags with type app/bt." );
    },
    function(){
        throw new appError( "Error establishing NDEF MimeType listener" );
    }
);

nfc.addMimeTypeListener(
    'app/ty',
    app.secondCallback,
    function() {
        console.log( "Listening for NDEF mime tags with type app/ty." );
    },
    function(){
        throw new appError( "Error establishing NDEF MimeType listener" );
    }
);

Adding 2 MimeType listeners in a deviceReady function executes the 2 callback functions when detecting a tag containing a 'app/bt' MimeType record, and no 'app/ty' MimeType record.

Do you think I misunderstood anything, or is it the 'normal' behaviour of the plugin ?

don commented 10 years ago

The plugin was designed to have registerMimeType called one time, but it can be called for multiple mime types.

phonegap-nfc doesn't pass return values through the success callback like may phonegap plugins (this is a legacy issue from phonegap 0.9.x)

nfc.addMimeTypeListener registers event listener for javascript ndef-mime events

var nfc = {

    addMimeTypeListener: function (mimeType, callback, win, fail) {
        document.addEventListener("ndef-mime", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerMimeType", [mimeType]);
    },

    ...

With Android 4.x is you use the same listener for multiple mimetypes, it appears to work OK and the listener is only called once.

    nfc.addMimeTypeListener("text/json", onNfc, success, failure);
    nfc.addMimeTypeListener("text/demo", onNfc, success, failure);

If you use different listeners BOTH listeners are called every time.

    nfc.addMimeTypeListener("text/json", onNfc, success, failure);
    nfc.addMimeTypeListener("text/demo", onNfc2, success, failure);

This is because the native Android code registers a filter for the mime type but throws the same ndef-mime javascript event for every tag.