community-cordova-plugin-nfc 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1020 @@
1
+ package com.chariotsolutions.nfc.plugin;
2
+
3
+ import java.io.IOException;
4
+ import java.lang.reflect.InvocationTargetException;
5
+ import java.lang.reflect.Method;
6
+ import java.util.ArrayList;
7
+ import java.util.Arrays;
8
+ import java.util.Iterator;
9
+ import java.util.List;
10
+
11
+ // using wildcard imports so we can support Cordova 3.x
12
+ import org.apache.cordova.*; // Cordova 3.x
13
+
14
+ import org.json.JSONArray;
15
+ import org.json.JSONException;
16
+ import org.json.JSONObject;
17
+
18
+ import android.app.Activity;
19
+ import android.app.PendingIntent;
20
+ import android.content.Intent;
21
+ import android.content.IntentFilter;
22
+ import android.content.IntentFilter.MalformedMimeTypeException;
23
+ import android.net.Uri;
24
+ import android.nfc.FormatException;
25
+ import android.nfc.NdefMessage;
26
+ import android.nfc.NdefRecord;
27
+ import android.nfc.NfcAdapter;
28
+ import android.nfc.NfcEvent;
29
+ import android.nfc.Tag;
30
+ import android.nfc.TagLostException;
31
+ import android.nfc.tech.Ndef;
32
+ import android.nfc.tech.NdefFormatable;
33
+ import android.nfc.tech.TagTechnology;
34
+ import android.os.Bundle;
35
+ import android.os.Parcelable;
36
+ import android.util.Log;
37
+
38
+ public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCompleteCallback {
39
+ private static final String REGISTER_MIME_TYPE = "registerMimeType";
40
+ private static final String REMOVE_MIME_TYPE = "removeMimeType";
41
+ private static final String REGISTER_NDEF = "registerNdef";
42
+ private static final String REMOVE_NDEF = "removeNdef";
43
+ private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable";
44
+ private static final String REGISTER_DEFAULT_TAG = "registerTag";
45
+ private static final String REMOVE_DEFAULT_TAG = "removeTag";
46
+ private static final String WRITE_TAG = "writeTag";
47
+ private static final String MAKE_READ_ONLY = "makeReadOnly";
48
+ private static final String ERASE_TAG = "eraseTag";
49
+ private static final String SHARE_TAG = "shareTag";
50
+ private static final String UNSHARE_TAG = "unshareTag";
51
+ private static final String HANDOVER = "handover"; // Android Beam
52
+ private static final String STOP_HANDOVER = "stopHandover";
53
+ private static final String ENABLED = "enabled";
54
+ private static final String INIT = "init";
55
+ private static final String SHOW_SETTINGS = "showSettings";
56
+
57
+ private static final String NDEF = "ndef";
58
+ private static final String NDEF_MIME = "ndef-mime";
59
+ private static final String NDEF_FORMATABLE = "ndef-formatable";
60
+ private static final String TAG_DEFAULT = "tag";
61
+
62
+ private static final String READER_MODE = "readerMode";
63
+ private static final String DISABLE_READER_MODE = "disableReaderMode";
64
+
65
+ // TagTechnology IsoDep, NfcA, NfcB, NfcV, NfcF, MifareClassic, MifareUltralight
66
+ private static final String CONNECT = "connect";
67
+ private static final String CLOSE = "close";
68
+ private static final String TRANSCEIVE = "transceive";
69
+ private TagTechnology tagTechnology = null;
70
+ private Class<?> tagTechnologyClass;
71
+
72
+ private static final String CHANNEL = "channel";
73
+
74
+ private static final String STATUS_NFC_OK = "NFC_OK";
75
+ private static final String STATUS_NO_NFC = "NO_NFC";
76
+ private static final String STATUS_NFC_DISABLED = "NFC_DISABLED";
77
+ private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED";
78
+
79
+ private static final String TAG = "NfcPlugin";
80
+ private final List<IntentFilter> intentFilters = new ArrayList<>();
81
+ private final ArrayList<String[]> techLists = new ArrayList<>();
82
+
83
+ private NdefMessage p2pMessage = null;
84
+ private PendingIntent pendingIntent = null;
85
+
86
+ private Intent savedIntent = null;
87
+
88
+ private CallbackContext readerModeCallback;
89
+ private CallbackContext channelCallback;
90
+ private CallbackContext shareTagCallback;
91
+ private CallbackContext handoverCallback;
92
+
93
+ @Override
94
+ public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
95
+
96
+ Log.d(TAG, "execute " + action);
97
+
98
+ // showSettings can be called if NFC is disabled
99
+ // might want to skip this if NO_NFC
100
+ if (action.equalsIgnoreCase(SHOW_SETTINGS)) {
101
+ showSettings(callbackContext);
102
+ return true;
103
+ }
104
+
105
+ // the channel is set up when the plugin starts
106
+ if (action.equalsIgnoreCase(CHANNEL)) {
107
+ channelCallback = callbackContext;
108
+ return true; // short circuit
109
+ }
110
+
111
+ // allow reader mode to be disabled even if nfc is disabled
112
+ if (action.equalsIgnoreCase(DISABLE_READER_MODE)) {
113
+ disableReaderMode(callbackContext);
114
+ return true; // short circuit
115
+ }
116
+
117
+ if (!getNfcStatus().equals(STATUS_NFC_OK)) {
118
+ callbackContext.error(getNfcStatus());
119
+ return true; // short circuit
120
+ }
121
+
122
+ createPendingIntent();
123
+
124
+ if (action.equalsIgnoreCase(READER_MODE)) {
125
+ int flags = data.getInt(0);
126
+ readerMode(flags, callbackContext);
127
+
128
+ } else if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) {
129
+ registerMimeType(data, callbackContext);
130
+
131
+ } else if (action.equalsIgnoreCase(REMOVE_MIME_TYPE)) {
132
+ removeMimeType(data, callbackContext);
133
+
134
+ } else if (action.equalsIgnoreCase(REGISTER_NDEF)) {
135
+ registerNdef(callbackContext);
136
+
137
+ } else if (action.equalsIgnoreCase(REMOVE_NDEF)) {
138
+ removeNdef(callbackContext);
139
+
140
+ } else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) {
141
+ registerNdefFormatable(callbackContext);
142
+
143
+ } else if (action.equals(REGISTER_DEFAULT_TAG)) {
144
+ registerDefaultTag(callbackContext);
145
+
146
+ } else if (action.equals(REMOVE_DEFAULT_TAG)) {
147
+ removeDefaultTag(callbackContext);
148
+
149
+ } else if (action.equalsIgnoreCase(WRITE_TAG)) {
150
+ writeTag(data, callbackContext);
151
+
152
+ } else if (action.equalsIgnoreCase(MAKE_READ_ONLY)) {
153
+ makeReadOnly(callbackContext);
154
+
155
+ } else if (action.equalsIgnoreCase(ERASE_TAG)) {
156
+ eraseTag(callbackContext);
157
+
158
+ } else if (action.equalsIgnoreCase(SHARE_TAG)) {
159
+ shareTag(data, callbackContext);
160
+
161
+ } else if (action.equalsIgnoreCase(UNSHARE_TAG)) {
162
+ unshareTag(callbackContext);
163
+
164
+ } else if (action.equalsIgnoreCase(HANDOVER)) {
165
+ handover(data, callbackContext);
166
+
167
+ } else if (action.equalsIgnoreCase(STOP_HANDOVER)) {
168
+ stopHandover(callbackContext);
169
+
170
+ } else if (action.equalsIgnoreCase(INIT)) {
171
+ init(callbackContext);
172
+
173
+ } else if (action.equalsIgnoreCase(ENABLED)) {
174
+ // status is checked before every call
175
+ // if code made it here, NFC is enabled
176
+ callbackContext.success(STATUS_NFC_OK);
177
+
178
+ } else if (action.equalsIgnoreCase(CONNECT)) {
179
+ String tech = data.getString(0);
180
+ int timeout = data.optInt(1, -1);
181
+ connect(tech, timeout, callbackContext);
182
+
183
+ } else if (action.equalsIgnoreCase(TRANSCEIVE)) {
184
+ CordovaArgs args = new CordovaArgs(data); // execute is using the old signature with JSON data
185
+
186
+ byte[] command = args.getArrayBuffer(0);
187
+ transceive(command, callbackContext);
188
+
189
+ } else if (action.equalsIgnoreCase(CLOSE)) {
190
+ close(callbackContext);
191
+
192
+ } else {
193
+ // invalid action
194
+ return false;
195
+ }
196
+
197
+ return true;
198
+ }
199
+
200
+ private String getNfcStatus() {
201
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
202
+ if (nfcAdapter == null) {
203
+ return STATUS_NO_NFC;
204
+ } else if (!nfcAdapter.isEnabled()) {
205
+ return STATUS_NFC_DISABLED;
206
+ } else {
207
+ return STATUS_NFC_OK;
208
+ }
209
+ }
210
+
211
+ private void readerMode(int flags, CallbackContext callbackContext) {
212
+ Bundle extras = new Bundle(); // not used
213
+ readerModeCallback = callbackContext;
214
+ getActivity().runOnUiThread(() -> {
215
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
216
+ nfcAdapter.enableReaderMode(getActivity(), callback, flags, extras);
217
+ });
218
+
219
+ }
220
+
221
+ private void disableReaderMode(CallbackContext callbackContext) {
222
+ getActivity().runOnUiThread(() -> {
223
+ readerModeCallback = null;
224
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
225
+ if (nfcAdapter != null) {
226
+ nfcAdapter.disableReaderMode(getActivity());
227
+ }
228
+ callbackContext.success();
229
+ });
230
+ }
231
+
232
+ private NfcAdapter.ReaderCallback callback = new NfcAdapter.ReaderCallback() {
233
+ @Override
234
+ public void onTagDiscovered(Tag tag) {
235
+
236
+ JSONObject json;
237
+
238
+ // If the tag supports Ndef, try and return an Ndef message
239
+ List<String> techList = Arrays.asList(tag.getTechList());
240
+ if (techList.contains(Ndef.class.getName())) {
241
+ Ndef ndef = Ndef.get(tag);
242
+ json = Util.ndefToJSON(ndef);
243
+ } else {
244
+ json = Util.tagToJSON(tag);
245
+ }
246
+
247
+ Intent tagIntent = new Intent();
248
+ tagIntent.putExtra(NfcAdapter.EXTRA_TAG, tag);
249
+ setIntent(tagIntent);
250
+
251
+ PluginResult result = new PluginResult(PluginResult.Status.OK, json);
252
+ result.setKeepCallback(true);
253
+ if (readerModeCallback != null) {
254
+ readerModeCallback.sendPluginResult(result);
255
+ } else {
256
+ Log.i(TAG, "readerModeCallback is null - reader mode probably disabled in the meantime");
257
+ }
258
+
259
+ }
260
+ };
261
+
262
+ private void registerDefaultTag(CallbackContext callbackContext) {
263
+ addTagFilter();
264
+ restartNfc();
265
+ callbackContext.success();
266
+ }
267
+
268
+ private void removeDefaultTag(CallbackContext callbackContext) {
269
+ removeTagFilter();
270
+ restartNfc();
271
+ callbackContext.success();
272
+ }
273
+
274
+ private void registerNdefFormatable(CallbackContext callbackContext) {
275
+ addTechList(new String[]{NdefFormatable.class.getName()});
276
+ restartNfc();
277
+ callbackContext.success();
278
+ }
279
+
280
+ private void registerNdef(CallbackContext callbackContext) {
281
+ addTechList(new String[]{Ndef.class.getName()});
282
+ restartNfc();
283
+ callbackContext.success();
284
+ }
285
+
286
+ private void removeNdef(CallbackContext callbackContext) {
287
+ removeTechList(new String[]{Ndef.class.getName()});
288
+ restartNfc();
289
+ callbackContext.success();
290
+ }
291
+
292
+ private void unshareTag(CallbackContext callbackContext) {
293
+ p2pMessage = null;
294
+ stopNdefPush();
295
+ shareTagCallback = null;
296
+ callbackContext.success();
297
+ }
298
+
299
+ private void init(CallbackContext callbackContext) {
300
+ Log.d(TAG, "Enabling plugin " + getIntent());
301
+
302
+ startNfc();
303
+ if (!recycledIntent()) {
304
+ parseMessage();
305
+ }
306
+ callbackContext.success();
307
+ }
308
+
309
+ private void removeMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException {
310
+ String mimeType = data.getString(0);
311
+ removeIntentFilter(mimeType);
312
+ restartNfc();
313
+ callbackContext.success();
314
+ }
315
+
316
+ private void registerMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException {
317
+ String mimeType = "";
318
+ try {
319
+ mimeType = data.getString(0);
320
+ intentFilters.add(createIntentFilter(mimeType));
321
+ restartNfc();
322
+ callbackContext.success();
323
+ } catch (MalformedMimeTypeException e) {
324
+ callbackContext.error("Invalid MIME Type " + mimeType);
325
+ }
326
+ }
327
+
328
+ // Cheating and writing an empty record. We may actually be able to erase some tag types.
329
+ private void eraseTag(CallbackContext callbackContext) {
330
+ Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
331
+ NdefRecord[] records = {
332
+ new NdefRecord(NdefRecord.TNF_EMPTY, new byte[0], new byte[0], new byte[0])
333
+ };
334
+ writeNdefMessage(new NdefMessage(records), tag, callbackContext);
335
+ }
336
+
337
+ private void writeTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
338
+ if (getIntent() == null) { // TODO remove this and handle LostTag
339
+ callbackContext.error("Failed to write tag, received null intent");
340
+ }
341
+
342
+ Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
343
+ NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
344
+ writeNdefMessage(new NdefMessage(records), tag, callbackContext);
345
+ }
346
+
347
+ private void writeNdefMessage(final NdefMessage message, final Tag tag, final CallbackContext callbackContext) {
348
+ cordova.getThreadPool().execute(() -> {
349
+ try {
350
+ Ndef ndef = Ndef.get(tag);
351
+ if (ndef != null) {
352
+ ndef.connect();
353
+
354
+ if (ndef.isWritable()) {
355
+ int size = message.toByteArray().length;
356
+ if (ndef.getMaxSize() < size) {
357
+ callbackContext.error("Tag capacity is " + ndef.getMaxSize() +
358
+ " bytes, message is " + size + " bytes.");
359
+ } else {
360
+ ndef.writeNdefMessage(message);
361
+ callbackContext.success();
362
+ }
363
+ } else {
364
+ callbackContext.error("Tag is read only");
365
+ }
366
+ ndef.close();
367
+ } else {
368
+ NdefFormatable formatable = NdefFormatable.get(tag);
369
+ if (formatable != null) {
370
+ formatable.connect();
371
+ formatable.format(message);
372
+ callbackContext.success();
373
+ formatable.close();
374
+ } else {
375
+ callbackContext.error("Tag doesn't support NDEF");
376
+ }
377
+ }
378
+ } catch (FormatException e) {
379
+ callbackContext.error(e.getMessage());
380
+ } catch (TagLostException e) {
381
+ callbackContext.error(e.getMessage());
382
+ } catch (IOException e) {
383
+ callbackContext.error(e.getMessage());
384
+ }
385
+ });
386
+ }
387
+
388
+ private void makeReadOnly(final CallbackContext callbackContext) {
389
+
390
+ if (getIntent() == null) { // Lost Tag
391
+ callbackContext.error("Failed to make tag read only, received null intent");
392
+ return;
393
+ }
394
+
395
+ final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
396
+ if (tag == null) {
397
+ callbackContext.error("Failed to make tag read only, tag is null");
398
+ return;
399
+ }
400
+
401
+ cordova.getThreadPool().execute(() -> {
402
+ boolean success = false;
403
+ String message = "Could not make tag read only";
404
+
405
+ Ndef ndef = Ndef.get(tag);
406
+
407
+ try {
408
+ if (ndef != null) {
409
+
410
+ ndef.connect();
411
+
412
+ if (!ndef.isWritable()) {
413
+ message = "Tag is not writable";
414
+ } else if (ndef.canMakeReadOnly()) {
415
+ success = ndef.makeReadOnly();
416
+ } else {
417
+ message = "Tag can not be made read only";
418
+ }
419
+
420
+ } else {
421
+ message = "Tag is not NDEF";
422
+ }
423
+
424
+ } catch (IOException e) {
425
+ Log.e(TAG, "Failed to make tag read only", e);
426
+ if (e.getMessage() != null) {
427
+ message = e.getMessage();
428
+ } else {
429
+ message = e.toString();
430
+ }
431
+ }
432
+
433
+ if (success) {
434
+ callbackContext.success();
435
+ } else {
436
+ callbackContext.error(message);
437
+ }
438
+ });
439
+ }
440
+
441
+ private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
442
+ NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
443
+ this.p2pMessage = new NdefMessage(records);
444
+
445
+ startNdefPush(callbackContext);
446
+ }
447
+
448
+ // setBeamPushUris
449
+ // Every Uri you provide must have either scheme 'file' or scheme 'content'.
450
+ // Note that this takes priority over setNdefPush
451
+ //
452
+ // See http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUris(android.net.Uri[],%20android.app.Activity)
453
+ private void handover(JSONArray data, CallbackContext callbackContext) throws JSONException {
454
+
455
+ Uri[] uri = new Uri[data.length()];
456
+
457
+ for (int i = 0; i < data.length(); i++) {
458
+ uri[i] = Uri.parse(data.getString(i));
459
+ }
460
+
461
+ startNdefBeam(callbackContext, uri);
462
+ }
463
+
464
+ private void stopHandover(CallbackContext callbackContext) {
465
+ stopNdefBeam();
466
+ handoverCallback = null;
467
+ callbackContext.success();
468
+ }
469
+
470
+ private void showSettings(CallbackContext callbackContext) {
471
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
472
+ Intent intent = new Intent(android.provider.Settings.ACTION_NFC_SETTINGS);
473
+ getActivity().startActivity(intent);
474
+ } else {
475
+ Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
476
+ getActivity().startActivity(intent);
477
+ }
478
+ callbackContext.success();
479
+ }
480
+
481
+ private void createPendingIntent() {
482
+ if (pendingIntent == null) {
483
+ Activity activity = getActivity();
484
+ Intent intent = new Intent(activity, activity.getClass());
485
+ intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
486
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
487
+ pendingIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_MUTABLE);
488
+ } else {
489
+ pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
490
+ }
491
+ }
492
+ }
493
+
494
+ private void addTechList(String[] list) {
495
+ this.addTechFilter();
496
+ this.addToTechList(list);
497
+ }
498
+
499
+ private void removeTechList(String[] list) {
500
+ this.removeTechFilter();
501
+ this.removeFromTechList(list);
502
+ }
503
+
504
+ private void addTechFilter() {
505
+ intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
506
+ }
507
+
508
+ private void removeTechFilter() {
509
+ Iterator<IntentFilter> iterator = intentFilters.iterator();
510
+ while (iterator.hasNext()) {
511
+ IntentFilter intentFilter = iterator.next();
512
+ if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intentFilter.getAction(0))) {
513
+ iterator.remove();
514
+ }
515
+ }
516
+ }
517
+
518
+ private void addTagFilter() {
519
+ intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));
520
+ }
521
+
522
+ private void removeTagFilter() {
523
+ Iterator<IntentFilter> iterator = intentFilters.iterator();
524
+ while (iterator.hasNext()) {
525
+ IntentFilter intentFilter = iterator.next();
526
+ if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intentFilter.getAction(0))) {
527
+ iterator.remove();
528
+ }
529
+ }
530
+ }
531
+
532
+ private void restartNfc() {
533
+ stopNfc();
534
+ startNfc();
535
+ }
536
+
537
+ private void startNfc() {
538
+ createPendingIntent(); // onResume can call startNfc before execute
539
+
540
+ getActivity().runOnUiThread(() -> {
541
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
542
+
543
+ if (nfcAdapter != null && !getActivity().isFinishing()) {
544
+ try {
545
+ IntentFilter[] intentFilters = getIntentFilters();
546
+ String[][] techLists = getTechLists();
547
+ // don't start NFC unless some intent filters or tech lists have been added,
548
+ // because empty lists act as wildcards and receives ALL scan events
549
+ if (intentFilters.length > 0 || techLists.length > 0) {
550
+ nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), intentFilters, techLists);
551
+ }
552
+
553
+ if (p2pMessage != null) {
554
+ nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
555
+ }
556
+ } catch (IllegalStateException e) {
557
+ // issue 110 - user exits app with home button while nfc is initializing
558
+ Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
559
+ }
560
+
561
+ }
562
+ });
563
+ }
564
+
565
+ private void stopNfc() {
566
+ Log.d(TAG, "stopNfc");
567
+ getActivity().runOnUiThread(() -> {
568
+
569
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
570
+
571
+ if (nfcAdapter != null) {
572
+ try {
573
+ nfcAdapter.disableForegroundDispatch(getActivity());
574
+ } catch (IllegalStateException e) {
575
+ // issue 125 - user exits app with back button while nfc
576
+ Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
577
+ }
578
+ }
579
+ });
580
+ }
581
+
582
+ private void startNdefBeam(final CallbackContext callbackContext, final Uri[] uris) {
583
+ getActivity().runOnUiThread(() -> {
584
+
585
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
586
+
587
+ if (nfcAdapter == null) {
588
+ callbackContext.error(STATUS_NO_NFC);
589
+ } else if (!nfcAdapter.isNdefPushEnabled()) {
590
+ callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
591
+ } else {
592
+ nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity());
593
+ try {
594
+ nfcAdapter.setBeamPushUris(uris, getActivity());
595
+
596
+ PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
597
+ result.setKeepCallback(true);
598
+ handoverCallback = callbackContext;
599
+ callbackContext.sendPluginResult(result);
600
+
601
+ } catch (IllegalArgumentException e) {
602
+ callbackContext.error(e.getMessage());
603
+ }
604
+ }
605
+ });
606
+ }
607
+
608
+ private void startNdefPush(final CallbackContext callbackContext) {
609
+ getActivity().runOnUiThread(() -> {
610
+
611
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
612
+
613
+ if (nfcAdapter == null) {
614
+ callbackContext.error(STATUS_NO_NFC);
615
+ } else if (!nfcAdapter.isNdefPushEnabled()) {
616
+ callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
617
+ } else {
618
+ nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
619
+ nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity());
620
+
621
+ PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
622
+ result.setKeepCallback(true);
623
+ shareTagCallback = callbackContext;
624
+ callbackContext.sendPluginResult(result);
625
+ }
626
+ });
627
+ }
628
+
629
+ private void stopNdefPush() {
630
+ getActivity().runOnUiThread(() -> {
631
+
632
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
633
+
634
+ if (nfcAdapter != null) {
635
+ nfcAdapter.setNdefPushMessage(null, getActivity());
636
+ }
637
+
638
+ });
639
+ }
640
+
641
+ private void stopNdefBeam() {
642
+ getActivity().runOnUiThread(() -> {
643
+
644
+ NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
645
+
646
+ if (nfcAdapter != null) {
647
+ nfcAdapter.setBeamPushUris(null, getActivity());
648
+ }
649
+
650
+ });
651
+ }
652
+
653
+ private void addToTechList(String[] techs) {
654
+ techLists.add(techs);
655
+ }
656
+
657
+ private void removeFromTechList(String[] techs) {
658
+ Iterator<String[]> iterator = techLists.iterator();
659
+ while (iterator.hasNext()) {
660
+ String[] list = iterator.next();
661
+ if (Arrays.equals(list, techs)) {
662
+ iterator.remove();
663
+ }
664
+ }
665
+ }
666
+
667
+ private void removeIntentFilter(String mimeType) {
668
+ Iterator<IntentFilter> iterator = intentFilters.iterator();
669
+ while (iterator.hasNext()) {
670
+ IntentFilter intentFilter = iterator.next();
671
+ String mt = intentFilter.getDataType(0);
672
+ if (mimeType.equals(mt)) {
673
+ iterator.remove();
674
+ }
675
+ }
676
+ }
677
+
678
+ private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException {
679
+ IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
680
+ intentFilter.addDataType(mimeType);
681
+ return intentFilter;
682
+ }
683
+
684
+ private PendingIntent getPendingIntent() {
685
+ return pendingIntent;
686
+ }
687
+
688
+ private IntentFilter[] getIntentFilters() {
689
+ return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
690
+ }
691
+
692
+ private String[][] getTechLists() {
693
+ //noinspection ToArrayCallWithZeroLengthArrayArgument
694
+ return techLists.toArray(new String[0][0]);
695
+ }
696
+
697
+ private void parseMessage() {
698
+ cordova.getThreadPool().execute(() -> {
699
+ Log.d(TAG, "parseMessage " + getIntent());
700
+ Intent intent = getIntent();
701
+ String action = intent.getAction();
702
+ Log.d(TAG, "action " + action);
703
+ if (action == null) {
704
+ return;
705
+ }
706
+
707
+ Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
708
+ Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
709
+
710
+ if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
711
+ Ndef ndef = Ndef.get(tag);
712
+ fireNdefEvent(NDEF_MIME, ndef, messages);
713
+
714
+ } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
715
+ for (String tagTech : tag.getTechList()) {
716
+ Log.d(TAG, tagTech);
717
+ if (tagTech.equals(NdefFormatable.class.getName())) {
718
+ fireNdefFormatableEvent(tag);
719
+ } else if (tagTech.equals(Ndef.class.getName())) { //
720
+ Ndef ndef = Ndef.get(tag);
721
+ fireNdefEvent(NDEF, ndef, messages);
722
+ }
723
+ }
724
+ }
725
+
726
+ if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
727
+ fireTagEvent(tag);
728
+ }
729
+
730
+ setIntent(new Intent());
731
+ });
732
+ }
733
+
734
+ // Send the event data through a channel so the JavaScript side can fire the event
735
+ private void sendEvent(String type, JSONObject tag) {
736
+
737
+ try {
738
+ JSONObject event = new JSONObject();
739
+ event.put("type", type); // TAG_DEFAULT, NDEF, NDEF_MIME, NDEF_FORMATABLE
740
+ event.put("tag", tag); // JSON representing the NFC tag and NDEF messages
741
+
742
+ PluginResult result = new PluginResult(PluginResult.Status.OK, event);
743
+ result.setKeepCallback(true);
744
+ channelCallback.sendPluginResult(result);
745
+ } catch (JSONException e) {
746
+ Log.e(TAG, "Error sending NFC event through the channel", e);
747
+ }
748
+
749
+ }
750
+
751
+ private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) {
752
+ JSONObject json = buildNdefJSON(ndef, messages);
753
+ sendEvent(type, json);
754
+ }
755
+
756
+ private void fireNdefFormatableEvent(Tag tag) {
757
+ sendEvent(NDEF_FORMATABLE, Util.tagToJSON(tag));
758
+ }
759
+
760
+ private void fireTagEvent(Tag tag) {
761
+ sendEvent(TAG_DEFAULT, Util.tagToJSON(tag));
762
+ }
763
+
764
+ private JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
765
+
766
+ JSONObject json = Util.ndefToJSON(ndef);
767
+
768
+ // ndef is null for peer-to-peer
769
+ // ndef and messages are null for ndef format-able
770
+ if (ndef == null && messages != null) {
771
+
772
+ try {
773
+
774
+ if (messages.length > 0) {
775
+ NdefMessage message = (NdefMessage) messages[0];
776
+ json.put("ndefMessage", Util.messageToJSON(message));
777
+ // guessing type, would prefer a more definitive way to determine type
778
+ json.put("type", "NDEF Push Protocol");
779
+ }
780
+
781
+ if (messages.length > 1) {
782
+ Log.wtf(TAG, "Expected one ndefMessage but found " + messages.length);
783
+ }
784
+
785
+ } catch (JSONException e) {
786
+ // shouldn't happen
787
+ Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
788
+ }
789
+ }
790
+ return json;
791
+ }
792
+
793
+ private boolean recycledIntent() { // TODO this is a kludge, find real solution
794
+
795
+ int flags = getIntent().getFlags();
796
+ if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) {
797
+ Log.i(TAG, "Launched from history, killing recycled intent");
798
+ setIntent(new Intent());
799
+ return true;
800
+ }
801
+ return false;
802
+ }
803
+
804
+ @Override
805
+ public void onPause(boolean multitasking) {
806
+ Log.d(TAG, "onPause " + getIntent());
807
+ super.onPause(multitasking);
808
+ if (multitasking) {
809
+ // nfc can't run in background
810
+ stopNfc();
811
+ }
812
+ }
813
+
814
+ @Override
815
+ public void onResume(boolean multitasking) {
816
+ Log.d(TAG, "onResume " + getIntent());
817
+ super.onResume(multitasking);
818
+ startNfc();
819
+ }
820
+
821
+ @Override
822
+ public void onNewIntent(Intent intent) {
823
+ Log.d(TAG, "onNewIntent " + intent);
824
+ super.onNewIntent(intent);
825
+ setIntent(intent);
826
+ savedIntent = intent;
827
+ parseMessage();
828
+ }
829
+
830
+ private Activity getActivity() {
831
+ return this.cordova.getActivity();
832
+ }
833
+
834
+ private Intent getIntent() {
835
+ return getActivity().getIntent();
836
+ }
837
+
838
+ private void setIntent(Intent intent) {
839
+ getActivity().setIntent(intent);
840
+ }
841
+
842
+ @Override
843
+ public void onNdefPushComplete(NfcEvent event) {
844
+
845
+ // handover (beam) take precedence over share tag (ndef push)
846
+ if (handoverCallback != null) {
847
+ PluginResult result = new PluginResult(PluginResult.Status.OK, "Beamed Message to Peer");
848
+ result.setKeepCallback(true);
849
+ handoverCallback.sendPluginResult(result);
850
+ } else if (shareTagCallback != null) {
851
+ PluginResult result = new PluginResult(PluginResult.Status.OK, "Shared Message with Peer");
852
+ result.setKeepCallback(true);
853
+ shareTagCallback.sendPluginResult(result);
854
+ }
855
+
856
+ }
857
+
858
+ /**
859
+ * Enable I/O operations to the tag from this TagTechnology object.
860
+ * *
861
+ *
862
+ * @param tech TagTechnology class name e.g. 'android.nfc.tech.IsoDep' or 'android.nfc.tech.NfcV'
863
+ * @param timeout tag timeout
864
+ * @param callbackContext Cordova callback context
865
+ */
866
+ private void connect(final String tech, final int timeout, final CallbackContext callbackContext) {
867
+ this.cordova.getThreadPool().execute(() -> {
868
+ try {
869
+
870
+ Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
871
+ if (tag == null && savedIntent != null) {
872
+ tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
873
+ }
874
+
875
+ if (tag == null) {
876
+ Log.e(TAG, "No Tag");
877
+ callbackContext.error("No Tag");
878
+ return;
879
+ }
880
+
881
+ JSONObject resultObject = new JSONObject();
882
+
883
+ // get technologies supported by this tag
884
+ List<String> techList = Arrays.asList(tag.getTechList());
885
+ if (techList.contains(tech)) {
886
+ // use reflection to call the static function Tech.get(tag)
887
+ tagTechnologyClass = Class.forName(tech);
888
+ Method method = tagTechnologyClass.getMethod("get", Tag.class);
889
+ tagTechnology = (TagTechnology) method.invoke(null, tag);
890
+
891
+ // If the tech supports it, return maxTransceiveLength and return it to the user
892
+ try {
893
+ Method maxTransceiveLengthMethod = tagTechnologyClass.getMethod("getMaxTransceiveLength");
894
+ resultObject.put("maxTransceiveLength", maxTransceiveLengthMethod.invoke(tagTechnology));
895
+ } catch(NoSuchMethodException e) {
896
+ // Some technologies do not support this, so just ignore.
897
+ } catch(JSONException e) {
898
+ Log.e(TAG, "Error serializing JSON", e);
899
+ }
900
+ }
901
+
902
+ if (tagTechnology == null) {
903
+ callbackContext.error("Tag does not support " + tech);
904
+ return;
905
+ }
906
+
907
+ tagTechnology.connect();
908
+ setTimeout(timeout);
909
+ callbackContext.success(resultObject);
910
+
911
+ } catch (IOException ex) {
912
+ Log.e(TAG, "Tag connection failed", ex);
913
+ callbackContext.error("Tag connection failed");
914
+
915
+ // Users should never get these reflection errors
916
+ } catch (ClassNotFoundException e) {
917
+ Log.e(TAG, e.getMessage(), e);
918
+ callbackContext.error(e.getMessage());
919
+ } catch (NoSuchMethodException e) {
920
+ Log.e(TAG, e.getMessage(), e);
921
+ callbackContext.error(e.getMessage());
922
+ } catch (IllegalAccessException e) {
923
+ Log.e(TAG, e.getMessage(), e);
924
+ callbackContext.error(e.getMessage());
925
+ } catch (InvocationTargetException e) {
926
+ Log.e(TAG, e.getMessage(), e);
927
+ callbackContext.error(e.getMessage());
928
+ }
929
+ });
930
+ }
931
+
932
+ // Call tagTech setTimeout with reflection or fail silently
933
+ private void setTimeout(int timeout) {
934
+ if (timeout < 0) {
935
+ return;
936
+ }
937
+ try {
938
+ Method setTimeout = tagTechnologyClass.getMethod("setTimeout", int.class);
939
+ setTimeout.invoke(tagTechnology, timeout);
940
+ } catch (NoSuchMethodException e) {
941
+ // ignore
942
+ } catch (IllegalAccessException e) {
943
+ // ignore
944
+ } catch (InvocationTargetException e) {
945
+ // ignore
946
+ }
947
+ }
948
+
949
+ /**
950
+ * Disable I/O operations to the tag from this TagTechnology object, and release resources.
951
+ *
952
+ * @param callbackContext Cordova callback context
953
+ */
954
+ private void close(CallbackContext callbackContext) {
955
+ cordova.getThreadPool().execute(() -> {
956
+ try {
957
+
958
+ if (tagTechnology != null && tagTechnology.isConnected()) {
959
+ tagTechnology.close();
960
+ tagTechnology = null;
961
+ callbackContext.success();
962
+ } else {
963
+ // connection already gone
964
+ callbackContext.success();
965
+ }
966
+
967
+ } catch (IOException ex) {
968
+ Log.e(TAG, "Error closing nfc connection", ex);
969
+ callbackContext.error("Error closing nfc connection " + ex.getLocalizedMessage());
970
+ }
971
+ });
972
+ }
973
+
974
+ /**
975
+ * Send raw commands to the tag and receive the response.
976
+ *
977
+ * @param data byte[] command to be passed to the tag
978
+ * @param callbackContext Cordova callback context
979
+ */
980
+ private void transceive(final byte[] data, final CallbackContext callbackContext) {
981
+ cordova.getThreadPool().execute(() -> {
982
+ try {
983
+ if (tagTechnology == null) {
984
+ Log.e(TAG, "No Tech");
985
+ callbackContext.error("No Tech");
986
+ return;
987
+ }
988
+ if (!tagTechnology.isConnected()) {
989
+ Log.e(TAG, "Not connected");
990
+ callbackContext.error("Not connected");
991
+ return;
992
+ }
993
+
994
+ // Use reflection so we can support many tag types
995
+ Method transceiveMethod = tagTechnologyClass.getMethod("transceive", byte[].class);
996
+ @SuppressWarnings("PrimitiveArrayArgumentToVarargsMethod")
997
+ byte[] response = (byte[]) transceiveMethod.invoke(tagTechnology, data);
998
+
999
+ callbackContext.success(response);
1000
+
1001
+ } catch (NoSuchMethodException e) {
1002
+ String error = "TagTechnology " + tagTechnologyClass.getName() + " does not have a transceive function";
1003
+ Log.e(TAG, error, e);
1004
+ callbackContext.error(error);
1005
+ } catch (NullPointerException e) {
1006
+ // This can happen if the tag has been closed while we're still working with it from the thread pool.
1007
+ Log.e(TAG, e.getMessage(), e);
1008
+ callbackContext.error(e.getMessage());
1009
+ } catch (IllegalAccessException e) {
1010
+ Log.e(TAG, e.getMessage(), e);
1011
+ callbackContext.error(e.getMessage());
1012
+ } catch (InvocationTargetException e) {
1013
+ Log.e(TAG, e.getMessage(), e);
1014
+ Throwable cause = e.getCause();
1015
+ callbackContext.error(cause.getMessage());
1016
+ }
1017
+ });
1018
+ }
1019
+
1020
+ }