Example usage for android.nfc NfcAdapter EXTRA_TAG

List of usage examples for android.nfc NfcAdapter EXTRA_TAG

Introduction

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

Prototype

String EXTRA_TAG

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

Click Source Link

Document

Mandatory extra containing the Tag that was discovered for the #ACTION_NDEF_DISCOVERED , #ACTION_TECH_DISCOVERED , and #ACTION_TAG_DISCOVERED intents.

Usage

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

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from   w  ww . ja v  a 2 s  .  c  om*/
    if (mInWriteMode) {
        if (intent != null) {
            String action = intent.getAction();
            if (mInWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                    && intent.hasExtra(EXTRA_DEVICE_NAME)) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String name = intent.getStringExtra(EXTRA_DEVICE_NAME);
                if ((tag != null) && (name != null)) {
                    // write the device and address
                    String lang = "en";
                    // don't write the passphrase!
                    byte[] textBytes = name.getBytes();
                    byte[] langBytes = null;
                    int langLength = 0;
                    try {
                        langBytes = lang.getBytes("US-ASCII");
                        langLength = langBytes.length;
                    } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, e.toString());
                    }
                    int textLength = textBytes.length;
                    byte[] payload = new byte[1 + langLength + textLength];

                    // set status byte (see NDEF spec for actual bits)
                    payload[0] = (byte) langLength;

                    // copy langbytes and textbytes into payload
                    if (langBytes != null) {
                        System.arraycopy(langBytes, 0, payload, 1, langLength);
                    }
                    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
                    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                            new byte[0], payload);
                    NdefMessage message = new NdefMessage(
                            new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()) });
                    // Get an instance of Ndef for the tag.
                    Ndef ndef = Ndef.get(tag);
                    if (ndef != null) {
                        try {
                            ndef.connect();
                            if (ndef.isWritable()) {
                                ndef.writeNdefMessage(message);
                            }
                            ndef.close();
                            Toast.makeText(this, "tag written", Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        } catch (FormatException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        NdefFormatable format = NdefFormatable.get(tag);
                        if (format != null) {
                            try {
                                format.connect();
                                format.format(message);
                                format.close();
                                Toast.makeText(getApplicationContext(), "tag written", Toast.LENGTH_LONG);
                            } catch (IOException e) {
                                Log.e(TAG, e.toString());
                            } catch (FormatException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    mNfcAdapter.disableForegroundDispatch(this);
                }
            }
        }
        mInWriteMode = false;
    } else {
        SharedPreferences sp = getSharedPreferences(KEY_PREFS, MODE_PRIVATE);
        onSharedPreferenceChanged(sp, KEY_DEVICES);
        // check if configuring a widget
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                final String[] displayNames = TapLock.getDeviceNames(mDevices);
                final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle("Select device for widget")
                            .setItems(displayNames, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // set the successful widget result
                                    Intent resultValue = new Intent();
                                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                                    setResult(RESULT_OK, resultValue);

                                    // broadcast the new widget to update
                                    JSONObject deviceJObj = mDevices.get(which);
                                    dialog.cancel();
                                    TapLockSettings.this.finish();
                                    try {
                                        sendBroadcast(TapLock
                                                .getPackageIntent(TapLockSettings.this, TapLockWidget.class)
                                                .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
                                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                                                .putExtra(EXTRA_DEVICE_NAME, deviceJObj.getString(KEY_NAME)));
                                    } catch (JSONException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                }
                            }).create();
                    mDialog.show();
                }
            }
        }
        // start the service before binding so that the service stays around for faster future connections
        startService(TapLock.getPackageIntent(this, TapLockService.class));
        bindService(TapLock.getPackageIntent(this, TapLockService.class), this, BIND_AUTO_CREATE);

        int serverVersion = sp.getInt(KEY_SERVER_VERSION, 0);
        if (mShowTapLockSettingsInfo && (mDevices.size() == 0)) {
            if (serverVersion < SERVER_VERSION)
                sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mShowTapLockSettingsInfo = false;
            Intent i = TapLock.getPackageIntent(this, TapLockInfo.class);
            i.putExtra(EXTRA_INFO, getString(R.string.info_taplocksettings));
            startActivity(i);
        } else if (serverVersion < SERVER_VERSION) {
            // TapLockServer has been updated
            sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_hasupdate)
                    .setMessage(R.string.msg_hasupdate)
                    .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                    .setTitle(R.string.msg_pickinstaller)
                                    .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                            final String installer_file = getResources()
                                                    .getStringArray(R.array.installer_values)[which];

                                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                                    .setTitle(R.string.msg_pickdownloader)
                                                    .setItems(R.array.download_entries,
                                                            new DialogInterface.OnClickListener() {

                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                    dialog.cancel();
                                                                    String action = getResources()
                                                                            .getStringArray(
                                                                                    R.array.download_values)[which];
                                                                    if (ACTION_DOWNLOAD_SDCARD.equals(action)
                                                                            && copyFileToSDCard(installer_file))
                                                                        Toast.makeText(TapLockSettings.this,
                                                                                "Done!", Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    else if (ACTION_DOWNLOAD_EMAIL
                                                                            .equals(action)
                                                                            && copyFileToSDCard(
                                                                                    installer_file)) {
                                                                        Intent emailIntent = new Intent(
                                                                                android.content.Intent.ACTION_SEND);
                                                                        emailIntent.setType(
                                                                                "application/java-archive");
                                                                        emailIntent.putExtra(Intent.EXTRA_TEXT,
                                                                                getString(
                                                                                        R.string.email_instructions));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_SUBJECT,
                                                                                getString(R.string.app_name));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_STREAM,
                                                                                Uri.parse("file://"
                                                                                        + Environment
                                                                                                .getExternalStorageDirectory()
                                                                                                .getPath()
                                                                                        + "/"
                                                                                        + installer_file));
                                                                        startActivity(Intent.createChooser(
                                                                                emailIntent, getString(
                                                                                        R.string.button_getserver)));
                                                                    }
                                                                }

                                                            })
                                                    .create();
                                            mDialog.show();
                                        }
                                    }).create();
                            mDialog.show();
                        }
                    }).create();
            mDialog.show();
        }
    }
}

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Handles an intent as received by the Activity, be it with a MAIN or an
 * NDEF_DISCOVERED action./*from w  w  w  . j  a  v a  2  s . com*/
 *
 * @param intent The intent to handle
 */
private void handleIntent(Intent intent) {
    String action = intent.getAction();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        // This is an "NFC tag scanned" intent
        String type = intent.getType();
        Log.d(TAG, "Read tag with type: " + type);

        if (MIME_VCARD.equals(type) || MIME_XVCARD.equals(type)) {
            if (mVCardEngine == null) {
                mVCardEngine = new VCardEngine();
            }

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                Ndef ndefTag = Ndef.get(tag);
                NdefMessage ndefMessage;

                // ndefTag can be null if the tag was INITIALIZED
                // but not actually written to
                if (ndefTag != null) {
                    ndefMessage = ndefTag.getCachedNdefMessage();
                    parseAndInsertVCard(ndefMessage);
                }
            }
        } else {
            Log.i(TAG, "Ignoring NDEF with mime type: " + type);
        }
    }

    // Nothing else to do if this is a MAIN intent...
}

From source file:com.nxp.nfc_demo.activities.MainActivity.java

public void doProcess(Intent nfc_intent) {
    mIntent = nfc_intent;//from ww w. j av a2  s. co  m
    Tag tag = nfc_intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    demo = new Ntag_I2C_Demo(tag, this, mPassword, mAuthStatus);
    if (demo.isReady()) {
        // Retrieve Auth Status before doing any operation
        mAuthStatus = obtainAuthStatus();
        String currTab = mTabHost.getCurrentTabTag();
        launchDemo(currTab);
    }
}

From source file:de.uni_koblenz_landau.apow.LoginActivity.java

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);/*from   w ww  . j  av  a 2 s .c o  m*/
    String action = intent.getAction();

    // If tag is detected, start reading it.
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) && MIME_TEXT_PLAIN.equals(intent.getType())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        readNFCTag(tag);
    }
}

From source file:de.uni_koblenz_landau.apow.PatientListActivity.java

@Override
protected void onNewIntent(Intent intent) {
    // If patients are updated, reload content and close search.
    if (intent.getBooleanExtra(ARG_CHANGED, false)) {
        searchPatients("", true);
        if (searchView != null) {
            searchView.setIconified(true);
        }/*from   w  w w  .  j  a  va 2s .c  o m*/
    }

    setIntent(intent);
    String action = intent.getAction();

    // If tag is detected, start reading it.
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        readNFCTag(tag);
    }
}

From source file:foundme.uniroma2.it.professore.HomeActivity.java

private void handleIntent(Intent intent) {
    String action = intent.getAction();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

        String type = intent.getType();
        if (Variables_it.MIME_TEXT_PLAIN.equals(type)) {

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            new NdefReaderTask().execute(tag);

        }//from  w ww .j av  a2s.c  om
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {

        // In questo caso usermo la Tech Discovered Intent
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String[] techList = tag.getTechList();
        String searchedTech = Ndef.class.getName();

        for (String tech : techList) {
            if (searchedTech.equals(tech)) {
                new NdefReaderTask().execute(tag);
                break;
            }
        }
    }
}

From source file:org.protocoderrunner.apprunner.AppRunnerActivity.java

@Override
public void onNewIntent(Intent intent) {
    MLog.d(TAG, "New intent " + intent);

    if (intent.getAction() != null) {
        MLog.d(TAG, "Discovered tag with intent: " + intent);
        // mText.setText("Discovered tag " + ++mCount + " with intent: " +
        // intent);

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String nfcID = StrUtils.bytetostring(tag.getId());

        // if there is mContext message waiting to be written
        if (PNFC.nfcMsg != null) {
            MLog.d(TAG, "->" + PNFC.nfcMsg);
            PNFC.writeTag(this, tag, PNFC.nfcMsg);
            onNFCWrittenListener.onNewTag();
            onNFCWrittenListener = null;
            PNFC.nfcMsg = null;//from w  w  w.  j  a  va 2 s .  c o  m

            // read the nfc tag info
        } else {

            // get NDEF tag details
            Ndef ndefTag = Ndef.get(tag);
            if (ndefTag == null) {
                return;
            }

            int size = ndefTag.getMaxSize(); // tag size
            boolean writable = ndefTag.isWritable(); // is tag writable?
            String type = ndefTag.getType(); // tag type

            String nfcMessage = "";

            // get NDEF message details
            NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
            if (ndefMesg != null) {
                NdefRecord[] ndefRecords = ndefMesg.getRecords();
                int len = ndefRecords.length;
                String[] recTypes = new String[len]; // will contain the
                // NDEF record types
                String[] recPayloads = new String[len]; // will contain the
                // NDEF record types
                for (int i = 0; i < len; i++) {
                    recTypes[i] = new String(ndefRecords[i].getType());
                    recPayloads[i] = new String(ndefRecords[i].getPayload());
                    MLog.d(TAG, "qq " + i + " " + recTypes[i] + " " + recPayloads[i]);

                }
                nfcMessage = recPayloads[0];

            }

            onNFCListener.onNewTag(nfcID, nfcMessage);
        }

    }

}

From source file:org.kegbot.app.HomeActivity.java

@Override
protected void onNewIntent(Intent intent) {
    Log.d(LOG_TAG, "onNewIntent: Got intent: " + intent);

    if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] id = tag.getId();
        if (id != null && id.length > 0) {
            String tagId = HexDump.toHexString(id).toLowerCase(Locale.US);
            Log.d(LOG_TAG, "Read NFC tag with id: " + tagId);
            // TODO: use tag technology as part of id?
            AuthenticatingActivity.startAndAuthenticate(this, "nfc", tagId);
        }//  w  w w.  j  av a  2s .c o m
    }
}

From source file:org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.NFCVideoBrowserActivity.java

/**
 * On create, process NDEF message with its intent action
 *  //w w  w.  ja  v a2  s . c  om
 * @param intent
 */
private String resolveIntent(Intent intent) {
    Log.d(CLASSNAME, "resolveIntent is called intent:" + intent.toString());
    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;
        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[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 };
        }

        return processNdefMessageArray(msgs);

    }

    return IParsedNdefCommand.COMMAND_UNKNOWN;
}

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

@Override
public void onNewIntent(Intent intent) {
    if (writeNfcEnabled) {
        // Handle the NFC part...

        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0);
        String text = preferences.getString("SSID", "N/A") + "||" + preferences.getString("password", "N/A");

        // create a new NdefRecord
        NdefRecord record = createMimeRecord("application/ch.bfh.instacircle", text.getBytes());

        // create a new Android Application Record
        NdefRecord aar = NdefRecord.createApplicationRecord(getPackageName());

        // create a ndef message
        NdefMessage message = new NdefMessage(new NdefRecord[] { record, aar });

        // extract tag from the intent
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        // write the tag
        writeTag(tag, message);/*  w  w w. j a va2s . co m*/

        // close the dialog
        writeNfcEnabled = false;
        writeNfcTagDialog.dismiss();
    }
}