From a8d18da75261d3a8b87352bbc5d9a38ade671394 Mon Sep 17 00:00:00 2001 From: EddyVerbruggen Date: Tue, 2 Jul 2019 17:16:36 +0200 Subject: [PATCH] 4.0.0 - Foreground dispatch can only be enabled when your activity is resumed #39 --- src/nfc.android.ts | 20 +++++++++++++------- src/package.json | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/nfc.android.ts b/src/nfc.android.ts index 3795564..e197e8a 100644 --- a/src/nfc.android.ts +++ b/src/nfc.android.ts @@ -256,6 +256,7 @@ export class Nfc implements NfcApi { private intentFilters: any; private techLists: any; private static firstInstance = true; + private started = false; constructor() { this.intentFilters = []; @@ -290,6 +291,7 @@ export class Nfc implements NfcApi { application.android.on(application.AndroidApplication.activityResumedEvent, (args: application.AndroidActivityEventData) => { let resumingNfcAdapter = android.nfc.NfcAdapter.getDefaultAdapter(args.activity); if (resumingNfcAdapter !== null && !args.activity.isFinishing()) { + this.started = true; resumingNfcAdapter.enableForegroundDispatch(args.activity, this.pendingIntent, this.intentFilters, this.techLists); // handle any pending intent nfcIntentHandler.parseMessage(); @@ -302,13 +304,17 @@ export class Nfc implements NfcApi { nfcIntentHandler.parseMessage(); }); - // on startup, we want to make sure the adapter is listening - let startupNfcAdapter = android.nfc.NfcAdapter.getDefaultAdapter(activity); - if (startupNfcAdapter !== null) { - startupNfcAdapter.enableForegroundDispatch(activity, this.pendingIntent, this.intentFilters, this.techLists); - // handle any pending intent - nfcIntentHandler.parseMessage(); - } + // on startup, we want to make sure the adapter is started, but the application must be active first, otherwise it will crash (so simply wrapping it in a timeout) + setTimeout(() => { + if (!this.started) { + let startupNfcAdapter = android.nfc.NfcAdapter.getDefaultAdapter(activity); + if (startupNfcAdapter !== null) { + startupNfcAdapter.enableForegroundDispatch(activity, this.pendingIntent, this.intentFilters, this.techLists); + // handle any pending intent + nfcIntentHandler.parseMessage(); + } + } + }, 3000); } } diff --git a/src/package.json b/src/package.json index bef5ed2..95158b5 100644 --- a/src/package.json +++ b/src/package.json @@ -1,6 +1,6 @@ { "name": "nativescript-nfc", - "version": "4.0.0", + "version": "4.0.1", "description": "NFC plugin for your NativeScript app", "main": "nfc", "typings": "index.d.ts",