List of usage examples for android.nfc.tech Ndef get
public static Ndef get(Tag tag)
From source file:com.sftoolworks.nfcoptions.SelectActivity.java
protected void writeSelection(Intent intent) { ListView list = (ListView) findViewById(R.id.listView1); if (list.getCount() == 0) return;//from w w w. ja v a 2 s. c o m try { Object[] results = ((OptionListAdapter) list.getAdapter()).getCheckedValues(); JSONObject obj = new JSONObject(); JSONArray array = new JSONArray(); if (null != results) { for (Object result : results) array.put(result.toString()); } obj.put("selection", array); obj.put("key", selectKey); SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE); // android studio (0.5.1) decorates this line as an error (some // of the time, anyway) but it's not an error. String identifier = sharedPref.getString(getString(R.string.user_id_key), ""); if (identifier.length() > 0) obj.put("user", identifier); String json = obj.toString(0); String outbound = "\u0002en"; outbound += json; NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, new byte[] { 'T' }, null, outbound.getBytes()); NdefMessage message = new NdefMessage(new NdefRecord[] { textRecord }); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Ndef ndef = Ndef.get(tag); ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); Toast.makeText(this, R.string.write_ok, Toast.LENGTH_LONG).show(); new Timer().schedule(new TimerTask() { @Override public void run() { finish(); } }, 1500); } catch (Exception e) { Log.d(TAG, e.toString()); String err = getString(R.string.tag_write_err) + "\n" + e.getMessage(); Toast.makeText(this, err, Toast.LENGTH_LONG).show(); } }
From source file:de.berlin.magun.nfcmime.core.RfidDAO.java
/** * Stores a NDEF into the {@link NdefMessageSingleton}. * @param tag//w ww .ja v a 2s. co m */ private void readRecords(Tag tag) { NdefSingleton.getInstance().setNdef(Ndef.get(tag)); // Create timestamp for NDEF message. long timestamp = (new Date()).getTime(); // Create ReadTask, which will the message into a Map in NdefMessageSingleton, identified by timestamp. ReadTask rt = new ReadTask(timestamp); IOThread readThread = new IOThread(); readThread.run(rt); // Retrieve NDEF message out of NdefMessageSingleton by it's timestamp ID, extract records. NdefMessage m = NdefMessageSingleton.getInstance().getMessage(timestamp); if (m != null) { this.records = NdefMessageSingleton.getInstance().getMessage(timestamp).getRecords(); } else { this.records = null; } }
From source file:org.openhab.habdroid.ui.OpenHABWriteTagActivity.java
private void writeTag(Tag tag, String uri) { Log.d(TAG, "Creating tag object for URI " + uri); TextView writeTagMessage = findViewById(R.id.write_tag_message); NdefRecord[] ndefRecords = new NdefRecord[] { NdefRecord.createUri(uri) }; NdefMessage message = new NdefMessage(ndefRecords); NdefFormatable ndefFormatable = NdefFormatable.get(tag); if (ndefFormatable != null) { Log.d(TAG, "Tag is uninitialized, formating"); try {/*from ww w . ja va 2 s.c o m*/ ndefFormatable.connect(); ndefFormatable.format(message); ndefFormatable.close(); writeTagMessage.setText(R.string.info_write_tag_finished); autoCloseActivity(); } catch (IOException | FormatException e) { Log.e(TAG, "Writing to unformatted tag failed: " + e); writeTagMessage.setText(R.string.info_write_failed); } } else { Log.d(TAG, "Tag is initialized, writing"); Ndef ndef = Ndef.get(tag); if (ndef != null) { try { Log.d(TAG, "Connecting"); ndef.connect(); Log.d(TAG, "Writing"); if (ndef.isWritable()) { ndef.writeNdefMessage(message); } Log.d(TAG, "Closing"); ndef.close(); writeTagMessage.setText(R.string.info_write_tag_finished); autoCloseActivity(); } catch (IOException | FormatException e) { Log.e(TAG, "Writing to formatted tag failed: " + e); writeTagMessage.setText(R.string.info_write_failed); } } else { Log.e(TAG, "Ndef == null"); writeTagMessage.setText(R.string.info_write_failed); } } }
From source file:de.berlin.magun.nfcmime.core.RfidDAO.java
/** * Writes an NDEF message on a NFC-compliant RFID transponder. * @param tag Tag/* w w w.ja v a 2s . c o m*/ * @param message the NdefMessage to write * @throws Exception */ public void writeMessage(Tag tag, NdefMessage message) throws Exception { // use NdefSingleton for I/O operations (which is also accessed by the separate Thread) NdefSingleton.getInstance().setNdef(Ndef.get(tag)); // make sure the tag can be written to if (!NdefSingleton.getInstance().getNdef().isWritable()) { throw new Exception("Tag is read-only!"); // TODO Create custom Exception for that purpose } // make sure the NDEF message is neither null, nor larger than the available tag memory if (message != null) { if (message.toByteArray().length > NdefSingleton.getInstance().getNdef().getMaxSize()) { throw new Exception("NDEF message too long!"); // TODO Create custom Exception for that purpose } } else { throw new NullPointerException(); } // create and run a IOThread that writes the message WriteTask wt = new WriteTask(message); IOThread writeThread = new IOThread(); writeThread.run(wt); }
From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java
/** * Handle incoming intents. Do not load a product if we already have one. *//* ww w .j a v a 2 s . c om*/ @Override protected void onResume() { super.onResume(); String[] options = { InternalConstants.PRODUCT_OPTION_BASIC, InternalConstants.PRODUCT_OPTION_CATEGORIES, InternalConstants.PRODUCT_OPTION_CLASSIFICATION, InternalConstants.PRODUCT_OPTION_DESCRIPTION, InternalConstants.PRODUCT_OPTION_GALLERY, InternalConstants.PRODUCT_OPTION_PRICE, InternalConstants.PRODUCT_OPTION_PROMOTIONS, InternalConstants.PRODUCT_OPTION_REVIEW, InternalConstants.PRODUCT_OPTION_STOCK, InternalConstants.PRODUCT_OPTION_VARIANT }; String productCode = null; Intent intent = getIntent(); // Direct Call if (intent.hasExtra(DataConstants.PRODUCT_CODE)) //direct call from search list for example { productCode = intent.getStringExtra(DataConstants.PRODUCT_CODE); } // NFC Call else if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) //NFC { Tag tag = getIntent().getExtras().getParcelable(NfcAdapter.EXTRA_TAG); Ndef ndef = Ndef.get(tag); NdefMessage message = ndef.getCachedNdefMessage(); NdefRecord record = message.getRecords()[0]; if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_URI)) { productCode = RegexUtil .getProductCode(new String(record.getPayload(), 1, record.getPayload().length - 1)); } } // Call from another application (QR Code) else if (StringUtils.equals(intent.getAction(), Intent.ACTION_VIEW)) { productCode = RegexUtil.getProductCode(intent.getDataString()); } if (StringUtils.isNotEmpty(productCode)) { this.enableAndroidBeam(productCode); } // Only load if we don't have a product already if (mProduct == null) { populateProduct(productCode, options); } invalidateOptionsMenu(); }
From source file:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java
private void write(Tag tag) throws IOException, FormatException { //generate new random key and write them on the tag SecureRandom sr = new SecureRandom(); sr.nextBytes(output);//w ww .j ava 2s . c om NdefRecord[] records = { createRecord(output.toString()) }; NdefMessage message = new NdefMessage(records); Ndef ndef = Ndef.get(tag); ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); }
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:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java
private String read(Tag tag) throws IOException, FormatException { //read string from tag String password = null;/*from www .j a v a 2s . co m*/ Ndef ndef = Ndef.get(tag); ndef.connect(); NdefMessage ndefMessage = ndef.getCachedNdefMessage(); NdefRecord[] records = ndefMessage.getRecords(); for (NdefRecord ndefRecord : records) { if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) { try { password = readText(ndefRecord); } catch (UnsupportedEncodingException e) { Log.e(Constants.TAG, "Failed to read password from tag", e); } } } ndef.close(); return password; }
From source file:mai.whack.StickyNotesActivity.java
boolean writeTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try {/* www.j av a 2 s .c o m*/ Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { toast("Tag is read-only."); return false; } if (ndef.getMaxSize() < size) { toast("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."); return false; } ndef.writeNdefMessage(message); toast("Wrote message to pre-formatted tag."); return true; } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); toast("Formatted tag and wrote message"); return true; } catch (IOException e) { toast("Failed to format tag."); return false; } } else { toast("Tag doesn't support NDEF."); return false; } } } catch (Exception e) { toast("Failed to write tag"); } return false; }
From source file:com.piusvelte.taplock.client.core.TapLockSettings.java
@Override protected void onResume() { super.onResume(); Intent intent = getIntent();//from w w w . j av 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(); } } }