Example usage for android.nfc NfcAdapter ACTION_TAG_DISCOVERED

List of usage examples for android.nfc NfcAdapter ACTION_TAG_DISCOVERED

Introduction

In this page you can find the example usage for android.nfc NfcAdapter ACTION_TAG_DISCOVERED.

Prototype

String ACTION_TAG_DISCOVERED

To view the source code for android.nfc NfcAdapter ACTION_TAG_DISCOVERED.

Click Source Link

Document

Intent to start an activity when a tag is discovered.

Usage

From source file:nl.hnogames.domoticz.NFCSettingsActivity.java

protected void onResume() {
    super.onResume();

    try {//from  w w w . j  a  v a2  s .  c  om
        // creating pending intent:
        PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // creating intent receiver for NFC events:
        IntentFilter filter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);

        // enabling foreground dispatch for getting intent from NFC event:
        if (mNfcAdapter == null) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

            if (mNfcAdapter != null) {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_register, Snackbar.LENGTH_SHORT);
            } else {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_not_supported,
                        Snackbar.LENGTH_SHORT);
            }
        }
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[] { filter },
                    this.techList);
    } catch (Exception ex) {
        Log.e(this.getClass().getSimpleName(), ex.getMessage());
    }
}

From source file:net.networksaremadeofstring.rhybudd.WriteNFCActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BugSenseHandler.initAndStartSession(WriteNFCActivity.this, "44a76a8c");

    setContentView(R.layout.write_tag_activity);

    try {/*from ww  w.  ja v a2  s  . c o m*/
        getActionBar().setSubtitle(getString(R.string.NFCTitle));
        getActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (Exception gab) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", gab);
    }

    //Quick test
    try {
        UID = getIntent().getExtras().getString(PAYLOAD_UID).replace("/zport/dmd/Devices/", "");

        aaRecord = NdefRecord.createApplicationRecord("net.networksaremadeofstring.rhybudd");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //idRecord = NdefRecord.createExternal("rhybudd:tag", "z", UID.getBytes(Charset.forName("US-ASCII")));
            idRecord = NdefRecord.createMime("application/vnd.rhybudd.device", UID.getBytes());
        } else {
            idRecord = NdefRecord.createUri("rhybudd://" + UID);
        }

        ((TextView) findViewById(R.id.SizesText)).setText("This payload is "
                + (aaRecord.toByteArray().length + idRecord.toByteArray().length)
                + " bytes.\n\nAn ultralight can store up to 46 bytes.\nAn Ultralight C or NTAG203 can store up to 137 bytes.\nDespite the name a 1K can only store up to 716 bytes.");
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        try {
            Toast.makeText(this, "Sorry there was error parsing the passed UID, we cannot continue.",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception t) {
            BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", t);
        }

        finish();
    }

    try {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate getDefaultAdapter", e);
        mAdapter = null;
    }

    try {
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate pendingIntent", e);
    }

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

    try {
        ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
                                    You should specify only the ones that you need. */
    } catch (IntentFilter.MalformedMimeTypeException e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        throw new RuntimeException("fail", e);
    }

    try {
        IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        intentFiltersArray = new IntentFilter[] { ndef, td };

        techListsArray = new String[][] { new String[] { NfcF.class.getName(), NfcA.class.getName(),
                Ndef.class.getName(), NdefFormatable.class.getName() } };
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate IntentFilter", e);
    }

    CreateHandlers();
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_network_active);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override/*from   w w  w. java2  s .com*/
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    // Handle the change of the Wifi configuration
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    adhoc = new AdhocWifiManager(wifi);
    wifiapmanager = new WifiAPManager();
    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

    // Is NFC available on this device?
    nfcAvailable = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC);

    // only set up the NFC stuff if NFC is also available
    if (nfcAvailable) {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter.isEnabled()) {

            // Setting up a pending intent that is invoked when an NFC tag
            // is tapped on the back
            pendingIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

            nfcIntentFilter = new IntentFilter();
            nfcIntentFilter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
            nfcIntentFilter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
            intentFiltersArray = new IntentFilter[] { nfcIntentFilter };
        } else {
            nfcAvailable = false;
        }
    }
}

From source file:se.anyro.nfc_reader.TagViewer.java

private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;/*from   ww  w .java 2s. co  m*/
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];

                // magic happens here
                processReadTag((NdefMessage) rawMsgs[i]);
            }

        } else {
            // Unknown tag type
            byte[] empty = new byte[0];
            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] payload = dumpTagData(tag).getBytes();
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            msgs = new NdefMessage[] { msg };
        }
        // Setup the views
        buildTagViews(msgs);
    }
}

From source file:io.atrac613.AbstractNfcTagFragment.java

@Override
public void onResume() {
    Log.d(TAG, "*** AbstractNfcFeliCaTagFragment go Resume");

    //foregrandDispathch
    Activity a = this.getActivity();
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    try {//w  ww  .jav a  2s  .co  m
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    IntentFilter[] filters = new IntentFilter[] { ndef, tag, tech };

    PendingIntent pendingIntent = PendingIntent.getActivity(a, 0,
            new Intent(a, a.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this.getActivity());

    adapter.enableForegroundDispatch(this.getActivity(), pendingIntent, filters, registerTechList(mTechList));

    super.onResume();
}

From source file:nl.hnogames.domoticz.NFCSettingsActivity.java

@Override
protected void onNewIntent(Intent intent) {
    if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED) && !busyWithTag) {
        boolean newTagFound = true;
        busyWithTag = true;/* ww w . j  av  a  2  s.  c  o m*/
        final String tagID = UsefulBits.ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
        if (nfcList != null && nfcList.size() > 0) {
            for (NFCInfo n : nfcList) {
                if (n.getId().equals(tagID))
                    newTagFound = false;
            }
        }

        if (newTagFound) {
            UsefulBits.showSnackbar(this, coordinatorLayout, getString(R.string.nfc_tag_found) + ": " + tagID,
                    Snackbar.LENGTH_SHORT);
            new MaterialDialog.Builder(this).title(R.string.nfc_tag_found).content(R.string.nfc_tag_name)
                    .inputType(InputType.TYPE_CLASS_TEXT)
                    .input(R.string.category_nfc, 0, new MaterialDialog.InputCallback() {
                        @Override
                        public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                            if (!UsefulBits.isEmpty(String.valueOf(input))) {
                                UsefulBits.showSnackbar(NFCSettingsActivity.this, coordinatorLayout,
                                        getString(R.string.nfc_saved) + ": " + input, Snackbar.LENGTH_SHORT);
                                NFCInfo newNFC = new NFCInfo();
                                newNFC.setId(tagID);
                                newNFC.setName(String.valueOf(input));
                                updateNFC(newNFC);
                            }
                            busyWithTag = false;
                        }
                    }).show();
        } else {
            UsefulBits.showSnackbar(NFCSettingsActivity.this, coordinatorLayout, R.string.nfc_exists,
                    Snackbar.LENGTH_SHORT);
            busyWithTag = false;
        }
    }
}

From source file:org.ndeftools.NfcDetectorActivity.java

/**
 * /* w  w  w.  j  a v  a  2s  . co m*/
 * Process the current intent, looking for NFC-related actions
 * 
 */

public void processIntent() {
    Intent intent = getIntent();
    // Check to see that the Activity started due to an Android Beam
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Log.d(TAG, "Process NDEF discovered action");

        nfcIntentDetected(intent, NfcAdapter.ACTION_NDEF_DISCOVERED);
    } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        Log.d(TAG, "Process APP_TAG discovered action");

        nfcIntentDetected(intent, NfcAdapter.ACTION_TAG_DISCOVERED);
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
        Log.d(TAG, "Process TECH discovered action");

        nfcIntentDetected(intent, NfcAdapter.ACTION_TECH_DISCOVERED);
    } else {
        Log.d(TAG, "Ignore action " + intent.getAction());
    }
}

From source file:com.nfc.gemkey.MainActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (DEBUG)/*  w  w w  .j  av a2 s  . c  o  m*/
        Log.d(TAG, "onNewIntent");

    final String action = intent.getAction();
    if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
        if (DEBUG)
            Log.i(TAG, "Discovered tag with intent: " + action);
        Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String nfc_tag_id = bytesToHexString(myTag.getId()).toUpperCase();
        tagId.setText("Tag ID : " + nfc_tag_id);

        if (mCheckTagInfoThread != null && mCheckTagInfoThread.isAlive()) {
            mCheckTagInfoThread.terminate();
            mCheckTagInfoThread = null;
        }
        mCheckTagInfoThread = new CheckTagInfoThread(nfc_tag_id);
        mCheckTagInfoThread.start();
    }
}

From source file:io.atrac613.AbstractNfcTagFragment.java

/**
 * ???//from  w w w.  j  av  a 2s. c om
 * @param intent ?????????
 */
public void onNewIntent(Intent intent) {
    String action = intent.getAction();
    Log.d(TAG, "incomming intent action = " + action);

    //TECHDISCOVERED
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        mNfcTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (mNfcTag != null) {
            String[] tagTechs = mNfcTag.getTechList();
            for (String[] filterTechs : mTechList) {
                if (ArrayUtil.containArray(tagTechs, filterTechs)) {
                    Log.d(TAG, "** nfcTag = " + mNfcTag.toString());
                    for (INfcTagListener listener : mListnerList) {
                        //?
                        listener.onTagDiscovered(intent, mNfcTag, this);
                    }
                }
            }
        }
    }
}

From source file:st.alr.homA.ActivityQuickpublishNfc.java

@Override
protected void onNewIntent(Intent intent) {
    Log.v(this.toString(), "write mode: " + writeMode);
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) && writeMode == true) {
        Tag mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Log.v(this.toString(), "Detected tag: " + mytag.toString());
        Log.v(this.toString(), "techlist:" + mytag.getTechList());

        ArrayList<Quickpublish> qps = adapter.getValues();
        if (qps.size() < 1) {
            publishProgress(getResources().getString(R.string.nfcWriteDialogTagNoContent), false);
            return;
        }//from w  w  w  . j  av a2 s .co m

        if (write(Quickpublish.toJsonString(qps), mytag)) {
            Log.v(this.toString(), "Write ok");
            publishProgress(getResources().getString(R.string.nfcWriteDialogTagSuccess), true);

        } else {
            Log.e(this.toString(), "Write fail");
        }
    }
}