Skip to content

Commit

Permalink
add a queue of Threads (aka channelWaitingQueue) that will be awake w…
Browse files Browse the repository at this point in the history
…hen the channel is ready
  • Loading branch information
paolosanchi committed Feb 11, 2021
1 parent 04f971f commit 617c7ba
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCom
private static final String TAG = "NfcPlugin";
private final List<IntentFilter> intentFilters = new ArrayList<>();
private final ArrayList<String[]> techLists = new ArrayList<>();
private final ArrayList<Thread> channelWaitingQueue = new ArrayList<>();

private NdefMessage p2pMessage = null;
private PendingIntent pendingIntent = null;
Expand All @@ -105,6 +106,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo
// the channel is set up when the plugin starts
if (action.equalsIgnoreCase(CHANNEL)) {
channelCallback = callbackContext;
awakeChannelWaitingQueue();
return true; // short circuit
}

Expand Down Expand Up @@ -197,6 +199,13 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo
return true;
}

private void awakeChannelWaitingQueue() {
for (Thread t: channelWaitingQueue) {
t.interrupt();
}
channelWaitingQueue.clear();
}

private String getNfcStatus() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter == null) {
Expand Down Expand Up @@ -737,14 +746,29 @@ private void sendEvent(String type, JSONObject tag) {

PluginResult result = new PluginResult(PluginResult.Status.OK, event);
result.setKeepCallback(true);
while(channelCallback == null) { }
waitForChannel();
channelCallback.sendPluginResult(result);
} catch (JSONException e) {
Log.e(TAG, "Error sending NFC event through the channel", e);
}

}

private void waitForChannel() {
if(channelCallback == null) {
channelWaitingQueue.add(Thread.currentThread());

while (channelCallback == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// the thread has been awakened, so channelCallback is set
return;
}
}
}
}

private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) {
JSONObject json = buildNdefJSON(ndef, messages);
sendEvent(type, json);
Expand Down

0 comments on commit 617c7ba

Please sign in to comment.