智能工厂.apk(点击下载) / NfcPlugin.java


package com.chariotsolutions.nfc.plugin;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.TagTechnology;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCompleteCallback {
    private static final String CHANNEL = "channel";
    private static final String CLOSE = "close";
    private static final String CONNECT = "connect";
    private static final String DISABLE_READER_MODE = "disableReaderMode";
    private static final String ENABLED = "enabled";
    private static final String ERASE_TAG = "eraseTag";
    private static final String HANDOVER = "handover";
    private static final String INIT = "init";
    private static final String MAKE_READ_ONLY = "makeReadOnly";
    private static final String NDEF = "ndef";
    private static final String NDEF_FORMATABLE = "ndef-formatable";
    private static final String NDEF_MIME = "ndef-mime";
    private static final String READER_MODE = "readerMode";
    private static final String REGISTER_DEFAULT_TAG = "registerTag";
    private static final String REGISTER_MIME_TYPE = "registerMimeType";
    private static final String REGISTER_NDEF = "registerNdef";
    private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable";
    private static final String REMOVE_DEFAULT_TAG = "removeTag";
    private static final String REMOVE_MIME_TYPE = "removeMimeType";
    private static final String REMOVE_NDEF = "removeNdef";
    private static final String SHARE_TAG = "shareTag";
    private static final String SHOW_SETTINGS = "showSettings";
    private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED";
    private static final String STATUS_NFC_DISABLED = "NFC_DISABLED";
    private static final String STATUS_NFC_OK = "NFC_OK";
    private static final String STATUS_NO_NFC = "NO_NFC";
    private static final String STOP_HANDOVER = "stopHandover";
    private static final String TAG = "NfcPlugin";
    private static final String TAG_DEFAULT = "tag";
    private static final String TRANSCEIVE = "transceive";
    private static final String UNSHARE_TAG = "unshareTag";
    private static final String WRITE_TAG = "writeTag";
    private NfcAdapter.ReaderCallback callback = new NfcAdapter.ReaderCallback() {
        /* class com.chariotsolutions.nfc.plugin.NfcPlugin.AnonymousClass1 */

        public void onTagDiscovered(Tag tag) {
            JSONObject jSONObject;
            if (Arrays.asList(tag.getTechList()).contains(Ndef.class.getName())) {
                jSONObject = Util.ndefToJSON(Ndef.get(tag));
            } else {
                jSONObject = Util.tagToJSON(tag);
            }
            Intent intent = new Intent();
            intent.putExtra("android.nfc.extra.TAG", tag);
            NfcPlugin.this.setIntent(intent);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jSONObject);
            pluginResult.setKeepCallback(true);
            if (NfcPlugin.this.readerModeCallback != null) {
                NfcPlugin.this.readerModeCallback.sendPluginResult(pluginResult);
            } else {
                Log.i(NfcPlugin.TAG, "readerModeCallback is null - reader mode probably disabled in the meantime");
            }
        }
    };
    private CallbackContext channelCallback;
    private CallbackContext handoverCallback;
    private final List<IntentFilter> intentFilters = new ArrayList();
    private NdefMessage p2pMessage = null;
    private PendingIntent pendingIntent = null;
    private CallbackContext readerModeCallback;
    private Intent savedIntent = null;
    private CallbackContext shareTagCallback;
    private TagTechnology tagTechnology = null;
    private Class<?> tagTechnologyClass;
    private final ArrayList<String[]> techLists = new ArrayList<>();

    @Override // org.apache.cordova.CordovaPlugin
    public boolean execute(String str, JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        Log.d(TAG, "execute " + str);
        if (str.equalsIgnoreCase(SHOW_SETTINGS)) {
            showSettings(callbackContext);
            return true;
        } else if (str.equalsIgnoreCase(CHANNEL)) {
            this.channelCallback = callbackContext;
            return true;
        } else if (str.equalsIgnoreCase(DISABLE_READER_MODE)) {
            disableReaderMode(callbackContext);
            return true;
        } else if (!getNfcStatus().equals(STATUS_NFC_OK)) {
            callbackContext.error(getNfcStatus());
            return true;
        } else {
            createPendingIntent();
            if (str.equalsIgnoreCase(READER_MODE)) {
                readerMode(jSONArray.getInt(0), callbackContext);
            } else if (str.equalsIgnoreCase(REGISTER_MIME_TYPE)) {
                registerMimeType(jSONArray, callbackContext);
            } else if (str.equalsIgnoreCase(REMOVE_MIME_TYPE)) {
                removeMimeType(jSONArray, callbackContext);
            } else if (str.equalsIgnoreCase(REGISTER_NDEF)) {
                registerNdef(callbackContext);
            } else if (str.equalsIgnoreCase(REMOVE_NDEF)) {
                removeNdef(callbackContext);
            } else if (str.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) {
                registerNdefFormatable(callbackContext);
            } else if (str.equals(REGISTER_DEFAULT_TAG)) {
                registerDefaultTag(callbackContext);
            } else if (str.equals(REMOVE_DEFAULT_TAG)) {
                removeDefaultTag(callbackContext);
            } else if (str.equalsIgnoreCase(WRITE_TAG)) {
                writeTag(jSONArray, callbackContext);
            } else if (str.equalsIgnoreCase(MAKE_READ_ONLY)) {
                makeReadOnly(callbackContext);
            } else if (str.equalsIgnoreCase(ERASE_TAG)) {
                eraseTag(callbackContext);
            } else if (str.equalsIgnoreCase(SHARE_TAG)) {
                shareTag(jSONArray, callbackContext);
            } else if (str.equalsIgnoreCase(UNSHARE_TAG)) {
                unshareTag(callbackContext);
            } else if (str.equalsIgnoreCase(HANDOVER)) {
                handover(jSONArray, callbackContext);
            } else if (str.equalsIgnoreCase(STOP_HANDOVER)) {
                stopHandover(callbackContext);
            } else if (str.equalsIgnoreCase(INIT)) {
                init(callbackContext);
            } else if (str.equalsIgnoreCase("enabled")) {
                callbackContext.success(STATUS_NFC_OK);
            } else if (str.equalsIgnoreCase(CONNECT)) {
                connect(jSONArray.getString(0), jSONArray.optInt(1, -1), callbackContext);
            } else if (str.equalsIgnoreCase(TRANSCEIVE)) {
                transceive(new CordovaArgs(jSONArray).getArrayBuffer(0), callbackContext);
            } else if (!str.equalsIgnoreCase(CLOSE)) {
                return false;
            } else {
                close(callbackContext);
            }
            return true;
        }
    }

    private String getNfcStatus() {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(getActivity());
        if (defaultAdapter == null) {
            return STATUS_NO_NFC;
        }
        return !defaultAdapter.isEnabled() ? STATUS_NFC_DISABLED : STATUS_NFC_OK;
    }

    private void readerMode(int i, CallbackContext callbackContext) {
        Bundle bundle = new Bundle();
        this.readerModeCallback = callbackContext;
        getActivity().runOnUiThread(new Runnable(i, bundle) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$77kw5Dnk4dBIYh0hIbTKMDB6shU */
            private final /* synthetic */ int f$1;
            private final /* synthetic */ Bundle f$2;

            {
                this.f$1 = r2;
                this.f$2 = r3;
            }

            public final void run() {
                NfcPlugin.lambda$readerMode$0(NfcPlugin.this, this.f$1, this.f$2);
            }
        });
    }

    private void disableReaderMode(CallbackContext callbackContext) {
        getActivity().runOnUiThread(new Runnable(callbackContext) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$TKDF8rIBP7hM0fk_E8tpgHY1pcY */
            private final /* synthetic */ CallbackContext f$1;

            {
                this.f$1 = r2;
            }

            public final void run() {
                NfcPlugin.lambda$disableReaderMode$1(NfcPlugin.this, this.f$1);
            }
        });
    }

    public static /* synthetic */ void lambda$disableReaderMode$1(NfcPlugin nfcPlugin, CallbackContext callbackContext) {
        nfcPlugin.readerModeCallback = null;
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter != null) {
            defaultAdapter.disableReaderMode(nfcPlugin.getActivity());
        }
        callbackContext.success();
    }

    private void registerDefaultTag(CallbackContext callbackContext) {
        addTagFilter();
        restartNfc();
        callbackContext.success();
    }

    private void removeDefaultTag(CallbackContext callbackContext) {
        removeTagFilter();
        restartNfc();
        callbackContext.success();
    }

    private void registerNdefFormatable(CallbackContext callbackContext) {
        addTechList(new String[]{NdefFormatable.class.getName()});
        restartNfc();
        callbackContext.success();
    }

    private void registerNdef(CallbackContext callbackContext) {
        addTechList(new String[]{Ndef.class.getName()});
        restartNfc();
        callbackContext.success();
    }

    private void removeNdef(CallbackContext callbackContext) {
        removeTechList(new String[]{Ndef.class.getName()});
        restartNfc();
        callbackContext.success();
    }

    private void unshareTag(CallbackContext callbackContext) {
        this.p2pMessage = null;
        stopNdefPush();
        this.shareTagCallback = null;
        callbackContext.success();
    }

    private void init(CallbackContext callbackContext) {
        Log.d(TAG, "Enabling plugin " + getIntent());
        startNfc();
        if (!recycledIntent()) {
            parseMessage();
        }
        callbackContext.success();
    }

    private void removeMimeType(JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        removeIntentFilter(jSONArray.getString(0));
        restartNfc();
        callbackContext.success();
    }

    private void registerMimeType(JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        String str = "";
        try {
            str = jSONArray.getString(0);
            this.intentFilters.add(createIntentFilter(str));
            restartNfc();
            callbackContext.success();
        } catch (IntentFilter.MalformedMimeTypeException unused) {
            callbackContext.error("Invalid MIME Type " + str);
        }
    }

    private void eraseTag(CallbackContext callbackContext) {
        writeNdefMessage(new NdefMessage(new NdefRecord[]{new NdefRecord(0, new byte[0], new byte[0], new byte[0])}), (Tag) this.savedIntent.getParcelableExtra("android.nfc.extra.TAG"), callbackContext);
    }

    private void writeTag(JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        if (getIntent() == null) {
            callbackContext.error("Failed to write tag, received null intent");
        }
        writeNdefMessage(new NdefMessage(Util.jsonToNdefRecords(jSONArray.getString(0))), (Tag) this.savedIntent.getParcelableExtra("android.nfc.extra.TAG"), callbackContext);
    }

    private void writeNdefMessage(NdefMessage ndefMessage, Tag tag, CallbackContext callbackContext) {
        this.f0cordova.getThreadPool().execute(new Runnable(tag, ndefMessage, callbackContext) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$V4Q2BP7F_8EoqcyBcDBJ2XVT1tY */
            private final /* synthetic */ Tag f$0;
            private final /* synthetic */ NdefMessage f$1;
            private final /* synthetic */ CallbackContext f$2;

            {
                this.f$0 = r1;
                this.f$1 = r2;
                this.f$2 = r3;
            }

            public final void run() {
                NfcPlugin.lambda$writeNdefMessage$2(this.f$0, this.f$1, this.f$2);
            }
        });
    }

    static /* synthetic */ void lambda$writeNdefMessage$2(Tag tag, NdefMessage ndefMessage, CallbackContext callbackContext) {
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();
                if (ndef.isWritable()) {
                    int length = ndefMessage.toByteArray().length;
                    if (ndef.getMaxSize() < length) {
                        callbackContext.error("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + length + " bytes.");
                    } else {
                        ndef.writeNdefMessage(ndefMessage);
                        callbackContext.success();
                    }
                } else {
                    callbackContext.error("Tag is read only");
                }
                ndef.close();
                return;
            }
            NdefFormatable ndefFormatable = NdefFormatable.get(tag);
            if (ndefFormatable != null) {
                ndefFormatable.connect();
                ndefFormatable.format(ndefMessage);
                callbackContext.success();
                ndefFormatable.close();
                return;
            }
            callbackContext.error("Tag doesn't support NDEF");
        } catch (FormatException e) {
            callbackContext.error(e.getMessage());
        } catch (TagLostException e2) {
            callbackContext.error(e2.getMessage());
        } catch (IOException e3) {
            callbackContext.error(e3.getMessage());
        }
    }

    private void makeReadOnly(CallbackContext callbackContext) {
        if (getIntent() == null) {
            callbackContext.error("Failed to make tag read only, received null intent");
            return;
        }
        Tag tag = (Tag) this.savedIntent.getParcelableExtra("android.nfc.extra.TAG");
        if (tag == null) {
            callbackContext.error("Failed to make tag read only, tag is null");
        } else {
            this.f0cordova.getThreadPool().execute(new Runnable(tag, callbackContext) {
                /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$2CYPepMVoRVwXPD_preob3THxKg */
                private final /* synthetic */ Tag f$0;
                private final /* synthetic */ CallbackContext f$1;

                {
                    this.f$0 = r1;
                    this.f$1 = r2;
                }

                public final void run() {
                    NfcPlugin.lambda$makeReadOnly$3(this.f$0, this.f$1);
                }
            });
        }
    }

    static /* synthetic */ void lambda$makeReadOnly$3(Tag tag, CallbackContext callbackContext) {
        String str = "Could not make tag read only";
        Ndef ndef = Ndef.get(tag);
        boolean z = false;
        if (ndef != null) {
            try {
                ndef.connect();
                if (!ndef.isWritable()) {
                    str = "Tag is not writable";
                } else if (ndef.canMakeReadOnly()) {
                    z = ndef.makeReadOnly();
                } else {
                    str = "Tag can not be made read only";
                }
            } catch (IOException e) {
                Log.e(TAG, "Failed to make tag read only", e);
                str = e.getMessage() != null ? e.getMessage() : e.toString();
            }
        } else {
            str = "Tag is not NDEF";
        }
        if (z) {
            callbackContext.success();
        } else {
            callbackContext.error(str);
        }
    }

    private void shareTag(JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        this.p2pMessage = new NdefMessage(Util.jsonToNdefRecords(jSONArray.getString(0)));
        startNdefPush(callbackContext);
    }

    private void handover(JSONArray jSONArray, CallbackContext callbackContext) throws JSONException {
        Uri[] uriArr = new Uri[jSONArray.length()];
        for (int i = 0; i < jSONArray.length(); i++) {
            uriArr[i] = Uri.parse(jSONArray.getString(i));
        }
        startNdefBeam(callbackContext, uriArr);
    }

    private void stopHandover(CallbackContext callbackContext) {
        stopNdefBeam();
        this.handoverCallback = null;
        callbackContext.success();
    }

    private void showSettings(CallbackContext callbackContext) {
        if (Build.VERSION.SDK_INT >= 16) {
            getActivity().startActivity(new Intent("android.settings.NFC_SETTINGS"));
        } else {
            getActivity().startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
        }
        callbackContext.success();
    }

    private void createPendingIntent() {
        if (this.pendingIntent == null) {
            Activity activity = getActivity();
            Intent intent = new Intent(activity, activity.getClass());
            intent.addFlags(603979776);
            this.pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
        }
    }

    private void addTechList(String[] strArr) {
        addTechFilter();
        addToTechList(strArr);
    }

    private void removeTechList(String[] strArr) {
        removeTechFilter();
        removeFromTechList(strArr);
    }

    private void addTechFilter() {
        this.intentFilters.add(new IntentFilter("android.nfc.action.TECH_DISCOVERED"));
    }

    private void removeTechFilter() {
        Iterator<IntentFilter> it = this.intentFilters.iterator();
        while (it.hasNext()) {
            if ("android.nfc.action.TECH_DISCOVERED".equals(it.next().getAction(0))) {
                it.remove();
            }
        }
    }

    private void addTagFilter() {
        this.intentFilters.add(new IntentFilter("android.nfc.action.TAG_DISCOVERED"));
    }

    private void removeTagFilter() {
        Iterator<IntentFilter> it = this.intentFilters.iterator();
        while (it.hasNext()) {
            if ("android.nfc.action.TAG_DISCOVERED".equals(it.next().getAction(0))) {
                it.remove();
            }
        }
    }

    private void restartNfc() {
        stopNfc();
        startNfc();
    }

    private void startNfc() {
        createPendingIntent();
        getActivity().runOnUiThread(new Runnable() {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$I3NCEv0XGTDPuMupw_E18QwHdkU */

            public final void run() {
                NfcPlugin.lambda$startNfc$4(NfcPlugin.this);
            }
        });
    }

    public static /* synthetic */ void lambda$startNfc$4(NfcPlugin nfcPlugin) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter != null && !nfcPlugin.getActivity().isFinishing()) {
            try {
                IntentFilter[] intentFilters2 = nfcPlugin.getIntentFilters();
                String[][] techLists2 = nfcPlugin.getTechLists();
                if (intentFilters2.length > 0 || techLists2.length > 0) {
                    defaultAdapter.enableForegroundDispatch(nfcPlugin.getActivity(), nfcPlugin.getPendingIntent(), intentFilters2, techLists2);
                }
                if (nfcPlugin.p2pMessage != null) {
                    defaultAdapter.setNdefPushMessage(nfcPlugin.p2pMessage, nfcPlugin.getActivity(), new Activity[0]);
                }
            } catch (IllegalStateException unused) {
                Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
            }
        }
    }

    private void stopNfc() {
        Log.d(TAG, "stopNfc");
        getActivity().runOnUiThread(new Runnable() {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$QSmnnvphwRyCdiPaQIHjEG0V74 */

            public final void run() {
                NfcPlugin.lambda$stopNfc$5(NfcPlugin.this);
            }
        });
    }

    public static /* synthetic */ void lambda$stopNfc$5(NfcPlugin nfcPlugin) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter != null) {
            try {
                defaultAdapter.disableForegroundDispatch(nfcPlugin.getActivity());
            } catch (IllegalStateException unused) {
                Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
            }
        }
    }

    private void startNdefBeam(CallbackContext callbackContext, Uri[] uriArr) {
        getActivity().runOnUiThread(new Runnable(callbackContext, uriArr) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$hOLeWoVVOcmEyVhKg8Cyhec9DK8 */
            private final /* synthetic */ CallbackContext f$1;
            private final /* synthetic */ Uri[] f$2;

            {
                this.f$1 = r2;
                this.f$2 = r3;
            }

            public final void run() {
                NfcPlugin.lambda$startNdefBeam$6(NfcPlugin.this, this.f$1, this.f$2);
            }
        });
    }

    public static /* synthetic */ void lambda$startNdefBeam$6(NfcPlugin nfcPlugin, CallbackContext callbackContext, Uri[] uriArr) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter == null) {
            callbackContext.error(STATUS_NO_NFC);
        } else if (!defaultAdapter.isNdefPushEnabled()) {
            callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
        } else {
            defaultAdapter.setOnNdefPushCompleteCallback(nfcPlugin, nfcPlugin.getActivity(), new Activity[0]);
            try {
                defaultAdapter.setBeamPushUris(uriArr, nfcPlugin.getActivity());
                PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
                pluginResult.setKeepCallback(true);
                nfcPlugin.handoverCallback = callbackContext;
                callbackContext.sendPluginResult(pluginResult);
            } catch (IllegalArgumentException e) {
                callbackContext.error(e.getMessage());
            }
        }
    }

    private void startNdefPush(CallbackContext callbackContext) {
        getActivity().runOnUiThread(new Runnable(callbackContext) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$idFLf0dIUDT5tLS6xNh44EKRdcU */
            private final /* synthetic */ CallbackContext f$1;

            {
                this.f$1 = r2;
            }

            public final void run() {
                NfcPlugin.lambda$startNdefPush$7(NfcPlugin.this, this.f$1);
            }
        });
    }

    public static /* synthetic */ void lambda$startNdefPush$7(NfcPlugin nfcPlugin, CallbackContext callbackContext) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter == null) {
            callbackContext.error(STATUS_NO_NFC);
        } else if (!defaultAdapter.isNdefPushEnabled()) {
            callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
        } else {
            defaultAdapter.setNdefPushMessage(nfcPlugin.p2pMessage, nfcPlugin.getActivity(), new Activity[0]);
            defaultAdapter.setOnNdefPushCompleteCallback(nfcPlugin, nfcPlugin.getActivity(), new Activity[0]);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            nfcPlugin.shareTagCallback = callbackContext;
            callbackContext.sendPluginResult(pluginResult);
        }
    }

    private void stopNdefPush() {
        getActivity().runOnUiThread(new Runnable() {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$9UQLaP0XxMSDuNgqxJVsL9BbUYk */

            public final void run() {
                NfcPlugin.lambda$stopNdefPush$8(NfcPlugin.this);
            }
        });
    }

    public static /* synthetic */ void lambda$stopNdefPush$8(NfcPlugin nfcPlugin) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter != null) {
            defaultAdapter.setNdefPushMessage(null, nfcPlugin.getActivity(), new Activity[0]);
        }
    }

    private void stopNdefBeam() {
        getActivity().runOnUiThread(new Runnable() {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$w1rShC_6h5EqOpBpFwt5FfQhCrM */

            public final void run() {
                NfcPlugin.lambda$stopNdefBeam$9(NfcPlugin.this);
            }
        });
    }

    public static /* synthetic */ void lambda$stopNdefBeam$9(NfcPlugin nfcPlugin) {
        NfcAdapter defaultAdapter = NfcAdapter.getDefaultAdapter(nfcPlugin.getActivity());
        if (defaultAdapter != null) {
            defaultAdapter.setBeamPushUris(null, nfcPlugin.getActivity());
        }
    }

    private void addToTechList(String[] strArr) {
        this.techLists.add(strArr);
    }

    private void removeFromTechList(String[] strArr) {
        Iterator<String[]> it = this.techLists.iterator();
        while (it.hasNext()) {
            if (Arrays.equals(it.next(), strArr)) {
                it.remove();
            }
        }
    }

    private void removeIntentFilter(String str) {
        Iterator<IntentFilter> it = this.intentFilters.iterator();
        while (it.hasNext()) {
            if (str.equals(it.next().getDataType(0))) {
                it.remove();
            }
        }
    }

    private IntentFilter createIntentFilter(String str) throws IntentFilter.MalformedMimeTypeException {
        IntentFilter intentFilter = new IntentFilter("android.nfc.action.NDEF_DISCOVERED");
        intentFilter.addDataType(str);
        return intentFilter;
    }

    private PendingIntent getPendingIntent() {
        return this.pendingIntent;
    }

    private IntentFilter[] getIntentFilters() {
        List<IntentFilter> list = this.intentFilters;
        return (IntentFilter[]) list.toArray(new IntentFilter[list.size()]);
    }

    private String[][] getTechLists() {
        return (String[][]) this.techLists.toArray((String[][]) Array.newInstance(String.class, 0, 0));
    }

    private void parseMessage() {
        this.f0cordova.getThreadPool().execute(new Runnable() {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$TZg0CG3DDDiSFVfSuGZc3CrxK4 */

            public final void run() {
                NfcPlugin.lambda$parseMessage$10(NfcPlugin.this);
            }
        });
    }

    public static /* synthetic */ void lambda$parseMessage$10(NfcPlugin nfcPlugin) {
        Log.d(TAG, "parseMessage " + nfcPlugin.getIntent());
        Intent intent = nfcPlugin.getIntent();
        String action = intent.getAction();
        Log.d(TAG, "action " + action);
        if (action != null) {
            Tag tag = (Tag) intent.getParcelableExtra("android.nfc.extra.TAG");
            Parcelable[] parcelableArrayExtra = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (action.equals("android.nfc.action.NDEF_DISCOVERED")) {
                nfcPlugin.fireNdefEvent(NDEF_MIME, Ndef.get(tag), parcelableArrayExtra);
            } else if (action.equals("android.nfc.action.TECH_DISCOVERED")) {
                String[] techList = tag.getTechList();
                for (String str : techList) {
                    Log.d(TAG, str);
                    if (str.equals(NdefFormatable.class.getName())) {
                        nfcPlugin.fireNdefFormatableEvent(tag);
                    } else if (str.equals(Ndef.class.getName())) {
                        nfcPlugin.fireNdefEvent(NDEF, Ndef.get(tag), parcelableArrayExtra);
                    }
                }
            }
            if (action.equals("android.nfc.action.TAG_DISCOVERED")) {
                nfcPlugin.fireTagEvent(tag);
            }
            nfcPlugin.setIntent(new Intent());
        }
    }

    private void sendEvent(String str, JSONObject jSONObject) {
        try {
            JSONObject jSONObject2 = new JSONObject();
            jSONObject2.put("type", str);
            jSONObject2.put(TAG_DEFAULT, jSONObject);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jSONObject2);
            pluginResult.setKeepCallback(true);
            this.channelCallback.sendPluginResult(pluginResult);
        } catch (JSONException e) {
            Log.e(TAG, "Error sending NFC event through the channel", e);
        }
    }

    private void fireNdefEvent(String str, Ndef ndef, Parcelable[] parcelableArr) {
        sendEvent(str, buildNdefJSON(ndef, parcelableArr));
    }

    private void fireNdefFormatableEvent(Tag tag) {
        sendEvent(NDEF_FORMATABLE, Util.tagToJSON(tag));
    }

    private void fireTagEvent(Tag tag) {
        sendEvent(TAG_DEFAULT, Util.tagToJSON(tag));
    }

    private JSONObject buildNdefJSON(Ndef ndef, Parcelable[] parcelableArr) {
        JSONObject ndefToJSON = Util.ndefToJSON(ndef);
        if (ndef == null && parcelableArr != null) {
            try {
                if (parcelableArr.length > 0) {
                    ndefToJSON.put("ndefMessage", Util.messageToJSON((NdefMessage) parcelableArr[0]));
                    ndefToJSON.put("type", "NDEF Push Protocol");
                }
                if (parcelableArr.length > 1) {
                    Log.wtf(TAG, "Expected one ndefMessage but found " + parcelableArr.length);
                }
            } catch (JSONException e) {
                Log.e(TAG, "Failed to convert ndefMessage into json", e);
            }
        }
        return ndefToJSON;
    }

    private boolean recycledIntent() {
        if ((getIntent().getFlags() & 1048576) != 1048576) {
            return false;
        }
        Log.i(TAG, "Launched from history, killing recycled intent");
        setIntent(new Intent());
        return true;
    }

    @Override // org.apache.cordova.CordovaPlugin
    public void onResume(boolean z) {
        Log.d(TAG, "onResume " + getIntent());
        super.onResume(z);
        startNfc();
    }

    @Override // org.apache.cordova.CordovaPlugin
    public void onNewIntent(Intent intent) {
        Log.d(TAG, "onNewIntent " + intent);
        super.onNewIntent(intent);
        setIntent(intent);
        this.savedIntent = intent;
        parseMessage();
    }

    private Activity getActivity() {
        return this.f0cordova.getActivity();
    }

    private Intent getIntent() {
        return getActivity().getIntent();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void setIntent(Intent intent) {
        getActivity().setIntent(intent);
    }

    public void onNdefPushComplete(NfcEvent nfcEvent) {
        if (this.handoverCallback != null) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "Beamed Message to Peer");
            pluginResult.setKeepCallback(true);
            this.handoverCallback.sendPluginResult(pluginResult);
        } else if (this.shareTagCallback != null) {
            PluginResult pluginResult2 = new PluginResult(PluginResult.Status.OK, "Shared Message with Peer");
            pluginResult2.setKeepCallback(true);
            this.shareTagCallback.sendPluginResult(pluginResult2);
        }
    }

    private void connect(String str, int i, CallbackContext callbackContext) {
        this.f0cordova.getThreadPool().execute(new Runnable(callbackContext, str, i) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$_1vZqtHzGydI1r1NZMLRk8NRk0Y */
            private final /* synthetic */ CallbackContext f$1;
            private final /* synthetic */ String f$2;
            private final /* synthetic */ int f$3;

            {
                this.f$1 = r2;
                this.f$2 = r3;
                this.f$3 = r4;
            }

            public final void run() {
                NfcPlugin.lambda$connect$11(NfcPlugin.this, this.f$1, this.f$2, this.f$3);
            }
        });
    }

    /* JADX WARNING: Code restructure failed: missing block: B:14:0x0079, code lost:
        r0 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:15:0x007a, code lost:
        android.util.Log.e(com.chariotsolutions.nfc.plugin.NfcPlugin.TAG, "Error serializing JSON", r0);
     */
    /* JADX WARNING: Code restructure failed: missing block: B:22:0x00a6, code lost:
        r10 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:23:0x00a7, code lost:
        android.util.Log.e(com.chariotsolutions.nfc.plugin.NfcPlugin.TAG, r10.getMessage(), r10);
        r9.error(r10.getMessage());
     */
    /* JADX WARNING: Code restructure failed: missing block: B:24:0x00b8, code lost:
        r10 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:25:0x00b9, code lost:
        android.util.Log.e(com.chariotsolutions.nfc.plugin.NfcPlugin.TAG, r10.getMessage(), r10);
        r9.error(r10.getMessage());
     */
    /* JADX WARNING: Code restructure failed: missing block: B:28:0x00dc, code lost:
        r10 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:29:0x00dd, code lost:
        android.util.Log.e(com.chariotsolutions.nfc.plugin.NfcPlugin.TAG, r10.getMessage(), r10);
        r9.error(r10.getMessage());
     */
    /* JADX WARNING: Code restructure failed: missing block: B:30:0x00ee, code lost:
        r10 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:31:0x00ef, code lost:
        android.util.Log.e(com.chariotsolutions.nfc.plugin.NfcPlugin.TAG, "Tag connection failed", r10);
        r9.error("Tag connection failed");
     */
    /* JADX WARNING: Code restructure failed: missing block: B:32:?, code lost:
        return;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:34:?, code lost:
        return;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:35:?, code lost:
        return;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:37:?, code lost:
        return;
     */
    /* JADX WARNING: Failed to process nested try/catch */
    /* JADX WARNING: Removed duplicated region for block: B:22:0x00a6 A[ExcHandler: InvocationTargetException (r10v9 'e' java.lang.reflect.InvocationTargetException A[CUSTOM_DECLARE]), Splitter:B:0:0x0000] */
    /* JADX WARNING: Removed duplicated region for block: B:24:0x00b8 A[ExcHandler: IllegalAccessException (r10v7 'e' java.lang.IllegalAccessException A[CUSTOM_DECLARE]), Splitter:B:0:0x0000] */
    /* JADX WARNING: Removed duplicated region for block: B:28:0x00dc A[ExcHandler: ClassNotFoundException (r10v3 'e' java.lang.ClassNotFoundException A[CUSTOM_DECLARE]), Splitter:B:0:0x0000] */
    /* JADX WARNING: Removed duplicated region for block: B:30:0x00ee A[ExcHandler: IOException (r10v1 'e' java.io.IOException A[CUSTOM_DECLARE]), Splitter:B:0:0x0000] */
    public static /* synthetic */ void lambda$connect$11(NfcPlugin nfcPlugin, CallbackContext callbackContext, String str, int i) {
        try {
            Tag tag = (Tag) nfcPlugin.getIntent().getParcelableExtra("android.nfc.extra.TAG");
            if (tag == null && nfcPlugin.savedIntent != null) {
                tag = (Tag) nfcPlugin.savedIntent.getParcelableExtra("android.nfc.extra.TAG");
            }
            if (tag == null) {
                Log.e(TAG, "No Tag");
                callbackContext.error("No Tag");
                return;
            }
            JSONObject jSONObject = new JSONObject();
            if (Arrays.asList(tag.getTechList()).contains(str)) {
                nfcPlugin.tagTechnologyClass = Class.forName(str);
                nfcPlugin.tagTechnology = (TagTechnology) nfcPlugin.tagTechnologyClass.getMethod("get", Tag.class).invoke(null, tag);
                jSONObject.put("maxTransceiveLength", nfcPlugin.tagTechnologyClass.getMethod("getMaxTransceiveLength", new Class[0]).invoke(nfcPlugin.tagTechnology, new Object[0]));
            }
            if (nfcPlugin.tagTechnology == null) {
                callbackContext.error("Tag does not support " + str);
                return;
            }
            nfcPlugin.tagTechnology.connect();
            nfcPlugin.setTimeout(i);
            callbackContext.success(jSONObject);
        } catch (IOException e) {
        } catch (ClassNotFoundException e2) {
        } catch (NoSuchMethodException e3) {
            Log.e(TAG, e3.getMessage(), e3);
            callbackContext.error(e3.getMessage());
        } catch (IllegalAccessException e4) {
        } catch (InvocationTargetException e5) {
        }
    }

    private void setTimeout(int i) {
        if (i >= 0) {
            try {
                this.tagTechnologyClass.getMethod("setTimeout", Integer.TYPE).invoke(this.tagTechnology, Integer.valueOf(i));
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException unused) {
            }
        }
    }

    private void close(CallbackContext callbackContext) {
        this.f0cordova.getThreadPool().execute(new Runnable(callbackContext) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$1BUl7Vlp8JbomJzGy45Bx3tAyy0 */
            private final /* synthetic */ CallbackContext f$1;

            {
                this.f$1 = r2;
            }

            public final void run() {
                NfcPlugin.lambda$close$12(NfcPlugin.this, this.f$1);
            }
        });
    }

    public static /* synthetic */ void lambda$close$12(NfcPlugin nfcPlugin, CallbackContext callbackContext) {
        try {
            if (nfcPlugin.tagTechnology == null || !nfcPlugin.tagTechnology.isConnected()) {
                callbackContext.success();
                return;
            }
            nfcPlugin.tagTechnology.close();
            nfcPlugin.tagTechnology = null;
            callbackContext.success();
        } catch (IOException e) {
            Log.e(TAG, "Error closing nfc connection", e);
            callbackContext.error("Error closing nfc connection " + e.getLocalizedMessage());
        }
    }

    private void transceive(byte[] bArr, CallbackContext callbackContext) {
        this.f0cordova.getThreadPool().execute(new Runnable(callbackContext, bArr) {
            /* class com.chariotsolutions.nfc.plugin.$$Lambda$NfcPlugin$hsKwiStihvBBzTUi3TVNxACGT14 */
            private final /* synthetic */ CallbackContext f$1;
            private final /* synthetic */ byte[] f$2;

            {
                this.f$1 = r2;
                this.f$2 = r3;
            }

            public final void run() {
                NfcPlugin.lambda$transceive$13(NfcPlugin.this, this.f$1, this.f$2);
            }
        });
    }

    public static /* synthetic */ void lambda$transceive$13(NfcPlugin nfcPlugin, CallbackContext callbackContext, byte[] bArr) {
        try {
            if (nfcPlugin.tagTechnology == null) {
                Log.e(TAG, "No Tech");
                callbackContext.error("No Tech");
            } else if (!nfcPlugin.tagTechnology.isConnected()) {
                Log.e(TAG, "Not connected");
                callbackContext.error("Not connected");
            } else {
                callbackContext.success((byte[]) nfcPlugin.tagTechnologyClass.getMethod(TRANSCEIVE, byte[].class).invoke(nfcPlugin.tagTechnology, bArr));
            }
        } catch (NoSuchMethodException e) {
            String str = "TagTechnology " + nfcPlugin.tagTechnologyClass.getName() + " does not have a transceive function";
            Log.e(TAG, str, e);
            callbackContext.error(str);
        } catch (NullPointerException e2) {
            Log.e(TAG, e2.getMessage(), e2);
            callbackContext.error(e2.getMessage());
        } catch (IllegalAccessException e3) {
            Log.e(TAG, e3.getMessage(), e3);
            callbackContext.error(e3.getMessage());
        } catch (InvocationTargetException e4) {
            Log.e(TAG, e4.getMessage(), e4);
            callbackContext.error(e4.getCause().getMessage());
        }
    }
}