Example usage for android.nfc NfcAdapter ACTION_NDEF_DISCOVERED

List of usage examples for android.nfc NfcAdapter ACTION_NDEF_DISCOVERED

Introduction

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

Prototype

String ACTION_NDEF_DISCOVERED

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

Click Source Link

Document

Intent to start an activity when a tag with NDEF payload is discovered.

Usage

From source file:mai.whack.StickyNotesActivity.java

@Override
protected void onNewIntent(Intent intent) {
    // NDEF exchange mode
    if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        onDataRead(intent);//  www . j a v a  2  s . c o m
    }

    // Tag writing mode
    if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        onDataWrite(intent);
    }
}

From source file:pl.edu.pw.eiti.groupbuying.partner.android.ClaimCouponsActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1 && getIntent() != null
            && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        processIntent(getIntent());/*ww w  .ja  v a2  s . c  o  m*/
    }

}

From source file:mai.whack.StickyNotesActivity.java

private void onDataRead(Intent intent) {
    // Parse the intent
    NdefMessage[] msgs = null;/*w ww  .  j a  va  2  s  .  co  m*/
    String action = intent.getAction();
    byte[] tagId = null;
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            // Unknown tag type
            byte[] empty = new byte[] {};
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            msgs = new NdefMessage[] { msg };
        }
    } else {
        Log.d(TAG, "Unknown intent.");
        finish();
    }

    String msg = new String(msgs[0].getRecords()[0].getPayload());
    mHttpGetThread = new HttpGetThread("http://192.168.1.192/store/" + toHex(tagId));
    mHttpGetThread.start();
    // mHttpPostThread = new HttpPostThread("aaaaa", "bbbbb", "sdgsdfdsfs");
    // mHttpPostThread.start();
}

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  w  w w .j  a  va 2s  .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:nl.hnogames.domoticz.NFCSettingsActivity.java

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

    try {/*from ww w  .j  a  v a  2 s . co  m*/
        // 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: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  www  .  j av  a 2s . c  o m*/
        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: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 {/*from   w  w w.  j ava  2  s  .  c  om*/
        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: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;// w  w w.ja va 2s.c  om
        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:com.example.mynsocial.BluetoothChat.java

@Override
public synchronized void onResume() {
    super.onResume();
    setupForegroundDispatch(this, mNfcAdapter);
    if (D)/*from  w w w  .  j av  a 2 s  . c o m*/
        Log.e(TAG, "+ ON RESUME +");

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        processIntent(getIntent());
        Log.e(TAG, "+++ ACTION +++");
    }

    if (mChatService != null) {
        // Only if the state is STATE_NONE, do we know that we haven't started already
        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
            mChatService.start();
        }
    }

    if (AccelerometerManager.isSupported(this)) {
        //Start Accelerometer Listening
        AccelerometerManager.startListening(this);
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockToggle.java

@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
    mServiceInterface = ITapLockService.Stub.asInterface(binder);
    if (mUIInterface != null) {
        try {//from  w  w w  . j  a  v  a 2 s .c o m
            mServiceInterface.setCallback(mUIInterface);
        } catch (RemoteException e) {
            Log.e(TAG, e.toString());
        }
    }
    Intent intent = getIntent();
    if (intent != null) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
                && intent.hasExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)) {
            Log.d(TAG, "service connected, NDEF_DISCOVERED");
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage message;
            if (rawMsgs != null) {
                // process the first message
                message = (NdefMessage) rawMsgs[0];
                // process the first record
                NdefRecord record = message.getRecords()[0];
                if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
                    try {
                        byte[] payload = record.getPayload();
                        /*
                         * payload[0] contains the "Status Byte Encodings" field, per the
                         * NFC Forum "Text Record Type Definition" section 3.2.1.
                         *
                         * bit7 is the Text Encoding Field.
                         *
                         * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
                         * The text is encoded in UTF16
                         *
                         * Bit_6 is reserved for future use and must be set to zero.
                         *
                         * Bits 5 to 0 are the length of the IANA language code.
                         */
                        String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
                        int languageCodeLength = payload[0] & 0077;
                        String taggedDeviceName = new String(payload, languageCodeLength + 1,
                                payload.length - languageCodeLength - 1, textEncoding);
                        manageDevice(taggedDeviceName, ACTION_TOGGLE);
                    } catch (UnsupportedEncodingException e) {
                        // should never happen unless we get a malformed tag.
                        Log.e(TAG, e.toString());
                        finish();
                    }
                } else
                    finish();
            } else
                finish();
        } else if (intent.getData() != null) {
            String taggedDeviceName = intent.getData().getHost();
            if (taggedDeviceName != null)
                manageDevice(taggedDeviceName, ACTION_TOGGLE);
            else
                finish();
        } else if (ACTION_UNLOCK.equals(action) || ACTION_LOCK.equals(action) || ACTION_TOGGLE.equals(action))
            manageDevice(intent.getStringExtra(EXTRA_DEVICE_NAME), action);
        else
            finish();
    } else
        finish();
}