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:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java

@Override
protected void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        if (writeNFC && CREATE_METHOD.equals(selectedAction)) {
            //write new password on NFC tag
            try {
                if (myTag != null) {
                    write(myTag);/*from  ww  w.  ja  v a  2 s. co  m*/
                    writeNFC = false; //just write once
                    Toast.makeText(this, R.string.nfc_write_succesful, Toast.LENGTH_SHORT).show();
                    //advance to lockpattern
                    //                        LockPatternFragmentOld lpf = LockPatternFragmentOld.newInstance(selectedAction);
                    //                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    //                        transaction.replace(R.id.fragmentContainer, lpf).addToBackStack(null).commit();
                }
            } catch (IOException | FormatException e) {
                Log.e(Constants.TAG, "Failed to write on NFC tag", e);
            }

        } else if (readNFC && AUTHENTICATION.equals(selectedAction)) {
            //read pw from NFC tag
            try {
                if (myTag != null) {
                    //if tag detected, read tag
                    String pwtag = read(myTag);
                    if (output != null && pwtag.equals(output.toString())) {

                        //passwort matches, go to next view
                        Toast.makeText(this, R.string.passphrases_match + "!", Toast.LENGTH_SHORT).show();

                        //                            LockPatternFragmentOld lpf = LockPatternFragmentOld.newInstance(selectedAction);
                        //                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        //                            transaction.replace(R.id.fragmentContainer, lpf).addToBackStack(null).commit();
                        readNFC = false; //just once
                    } else {
                        //passwort doesnt match
                        TextView nfc = (TextView) findViewById(R.id.nfcText);
                        nfc.setText(R.string.nfc_wrong_tag);
                    }
                }
            } catch (IOException | FormatException e) {
                Log.e(Constants.TAG, "Failed to read NFC tag", e);
            }
        }
    }
}

From source file:com.sigilance.CardEdit.MainActivity.java

/**
 * Receive new NFC Intents to this activity only by enabling foreground dispatch.
 * This can only be done in onResume!/* w w w  .jav a  2 s .c  o  m*/
 */
public void enableNfcForegroundDispatch() {
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        return;
    }
    Intent nfcI = new Intent(this, getClass())
            .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, nfcI,
            PendingIntent.FLAG_CANCEL_CURRENT);
    IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };

    try {
        mNfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
    } catch (IllegalStateException e) {
        Toast.makeText(this, "NfcForegroundDispatch Error!", Toast.LENGTH_LONG).show();
    }
}

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

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();//from www  . j  a v  a  2  s .  c  o m
    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:mai.whack.StickyNotesActivity.java

private void enableTagWriteMode() {
    mWriteMode = true;/*w  ww. j  av a  2 s  . c  o  m*/
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    mWriteTagFilters = new IntentFilter[] { tagDetected };
    mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
}

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  va2s .co 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:de.uni_koblenz_landau.apow.PatientListActivity.java

/**
 * Start scanning for NFC tags./*from   w w  w  . ja  v  a  2  s.  c o  m*/
  * @param activity The Activity requesting to the foreground dispatch.
  * @param adapter The NfcAdapter used for the foreground dispatch.
 */
private static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    if (adapter != null) {
        // Add intents for NFC.
        final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0,
                intent, 0);

        IntentFilter[] filters = new IntentFilter[1];
        String[][] techList = new String[][] {};

        filters[0] = new IntentFilter();
        filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filters[0].addCategory(Intent.CATEGORY_DEFAULT);

        adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
    }
}

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

/**
 * On create, process NDEF message with its intent action
 *  /*  w ww  . ja  v  a  2 s.  c o m*/
 * @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:be.brunoparmentier.wifikeyshare.ui.activities.WifiNetworkActivity.java

private void setupForegroundDispatch() {
    /* initialize the PendingIntent to start for the dispatch */
    nfcPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    /* initialize the IntentFilters to override dispatching for */
    nfcIntentFilters = new IntentFilter[3];
    nfcIntentFilters[0] = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    nfcIntentFilters[0].addCategory(Intent.CATEGORY_DEFAULT);
    nfcIntentFilters[1] = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    nfcIntentFilters[1].addCategory(Intent.CATEGORY_DEFAULT);
    nfcIntentFilters[2] = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    nfcIntentFilters[2].addCategory(Intent.CATEGORY_DEFAULT);
    try {/*w w w  . j ava  2s.  c  om*/
        nfcIntentFilters[0].addDataType("*/*"); // Handle all MIME based dispatches.
    } catch (IntentFilter.MalformedMimeTypeException e) {
        Log.e(TAG, "setupForegroundDispatch: " + e.getMessage());
    }

    /* Initialize the tech lists used to perform matching for dispatching of the
     * ACTION_TECH_DISCOVERED intent */
    nfcTechLists = new String[][] {};
}

From source file:be.brunoparmentier.wifikeyshare.ui.activities.WifiNetworkActivity.java

private void handleIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    String action = intent.getAction();
    Log.d(TAG, "handleIntent: action=" + action);
    if (isInWriteMode) {
        /* Write tag */
        Log.d(TAG, "Writing tag");
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

            if (NfcUtils.writeTag(wifiNetwork, tag)) {
                Toast.makeText(this, R.string.nfc_tag_written, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, R.string.error_nfc_tag_write, Toast.LENGTH_LONG).show();
            }//ww w .j av  a  2s .c o m
            disableTagWriteMode();
        }
    } else {
        /* Read tag */
        Log.d(TAG, "Reading tag");

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            if (NfcUtils.NFC_TOKEN_MIME_TYPE.equals(intent.getType())) {
                Intent configureNetworkIntent = new Intent(intent)
                        .setClass(this, ConfirmConnectToWifiNetworkActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(configureNetworkIntent);
            } else {
                Log.d(TAG, "Not a Wi-Fi configuration tag");
            }
        }
    }
}