List of usage examples for android.nfc.tech NdefFormatable format
public void format(NdefMessage firstMessage) throws IOException, FormatException
From source file:Main.java
public static boolean writeNFCTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try {// w w w . j a va 2 s .co m Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { return false; } if (ndef.getMaxSize() < size) { return false; } ndef.writeNdefMessage(message); return true; } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); return true; } catch (IOException e) { return false; } } else { return false; } } } catch (Exception e) { return false; } }
From source file:jp.co.brilliantservice.android.writertdtext.HomeActivity.java
/** * NdefFormatableNdef???NdefMessage????? * /*w w w. j a v a 2 s . com*/ * @param ndef * @param message */ private void writeNdefToNdefFormatable(NdefFormatable ndef, NdefMessage message) { try { ndef.connect(); ndef.format(message); } catch (IOException e) { throw new RuntimeException(e); } catch (FormatException e) { throw new RuntimeException(e); } finally { try { ndef.close(); } catch (IOException e) { // ignore } } }
From source file:com.macleod2486.androidswissknife.components.NFCCallback.java
@Override public void onTagDiscovered(Tag tag) { EditText tagResult = activity.findViewById(R.id.textEntry); try {// w w w . j av a 2 s. c o m Ndef ndef = Ndef.get(tag); if (ndef != null) { NdefMessage ndefMesg = ndef.getCachedNdefMessage(); if (ndefMesg != null) { nfcData = "Message: " + ndefMesg.toString(); Log.i("NFCCallback", nfcData); } } else { nfcData = "Attempting to format"; Log.i("NFCCallback", "Attempting to format"); activity.runOnUiThread(new Runnable() { @Override public void run() { tagResult.setText(""); tagResult.append("Attempting to format"); } }); NdefFormatable format = NdefFormatable.get(tag); if (format != null) { format.connect(); if (format.isConnected()) { try { format.format(null); nfcData = "Formatted"; Log.i("NFCCallback", "Formatted"); } catch (Exception e) { nfcData = "Error occurred in formatting"; e.printStackTrace(); } format.close(); } } else { Log.i("NFCCallback", "Tag not found"); nfcData = "Tag not found or formatted"; } } if (tagResult != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { tagResult.setText(""); Log.i("NFCCallback", "Cleared"); tagResult.append(nfcData); } }); } } catch (Exception e) { activity.runOnUiThread(new Runnable() { @Override public void run() { tagResult.setText(""); tagResult.append("Error reading tag"); } }); e.printStackTrace(); } }
From source file:com.hybris.mobile.activity.NFCWriteActivity.java
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // default failed setResult(RESULT_CANCELED);/*from www. j av a 2 s . c om*/ if (NFCUtil.supportsNdef(tag)) { Ndef ndef = Ndef.get(tag); try { int maxSize = ndef.getMaxSize(); int messageSize = this.msg.toByteArray().length; if (ndef.isWritable() && maxSize > messageSize) { ndef.connect(); ndef.writeNdefMessage(this.msg); if (getResources().getBoolean(R.bool.nfc_read_only)) { if (ndef.canMakeReadOnly()) { boolean success = ndef.makeReadOnly(); if (!success) Toast.makeText(this, "Unable to make tag readonly!", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Tag is now readonly!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "This tag cannot be made readonly!", Toast.LENGTH_LONG).show(); } } setResult(RESULT_OK); showDialogFragmentWithMessage(R.string.nfc_tag_written); } else { showDialogFragmentWithMessage(R.string.error_nfc_readonly_size); } } catch (IOException e) { LoggingUtils.e(LOG_CAT, getString(R.string.error_nfc_io), e, Hybris.getAppContext()); } catch (FormatException e) { LoggingUtils.e(LOG_CAT, getString(R.string.error_nfc_format), e, Hybris.getAppContext()); } finally { try { ndef.close(); } catch (IOException e) { } } } else if (NFCUtil.supportsNdefFormatable(tag)) { NdefFormatable ndefFormatable = NdefFormatable.get(tag); try { ndefFormatable.connect(); if (getResources().getBoolean(R.bool.nfc_read_only)) { ndefFormatable.formatReadOnly(this.msg); } else { ndefFormatable.format(this.msg); } setResult(RESULT_OK); showDialogFragmentWithMessage(R.string.nfc_tag_written); } catch (IOException e) { LoggingUtils.e(LOG_CAT, getString(R.string.error_nfc_io), e, Hybris.getAppContext()); } catch (FormatException e) { LoggingUtils.e(LOG_CAT, getString(R.string.error_nfc_format), e, Hybris.getAppContext()); } finally { try { ndefFormatable.close(); } catch (IOException e) { } } } else { showDialogFragmentWithMessage(R.string.error_nfc_no_ndef); } }
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 w w w.j av a 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:net.networksaremadeofstring.rhybudd.WriteNFCActivity.java
public void WriteTag(final Tag receivedTag) { tagHandler.sendEmptyMessage(TAG_IO_IN_PROGRESS); (new Thread() { public void run() { //This could go all kinds of weird Ndef thisNdef = null;/*from ww w . j a v a 2 s .c o m*/ try { thisNdef = Ndef.get(receivedTag); } catch (Exception e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); e.printStackTrace(); } if (null == thisNdef) { NdefFormatable formatter = null; try { formatter = NdefFormatable.get(receivedTag); formatter.connect(); formatter.format( new NdefMessage(new NdefRecord[] { NdefRecord.createApplicationRecord("io.d0") })); formatter.close(); thisNdef = Ndef.get(receivedTag); } catch (Exception d) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", d); d.printStackTrace(); tagHandler.sendEmptyMessage(FORMATEXCEPTION); } } try { if (null == thisNdef) { throw new FormatException("No NDEF Tag returned from get"); } else { thisNdef.connect(); } if (thisNdef.isWritable()) { //Is this a 203 or larger? if (thisNdef.getMaxSize() < aaRecord.toByteArray().length + idRecord.toByteArray().length) { /*Log.i("WriteTag","This tag was too big. tried to write " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize()); idRecord = NdefRecord.createMime("text/plain", Integer.toString(tagMetaData.getInt("i")).getBytes(Charset.forName("US-ASCII"))); Log.i("WriteTag Size Check", "Writing " + (idRecord.toByteArray().length + aaRecord.toByteArray().length) + " to " + thisNdef.getMaxSize());*/ tagHandler.sendEmptyMessage(SIZE_ERROR); } else { //Log.i("WriteTag Size Check", "Writing " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize()); NdefMessage tagMsg = new NdefMessage(new NdefRecord[] { idRecord, aaRecord }); //Log.i("WriteTag Size Check", "Wrote " + tagMsg.getByteArrayLength()); thisNdef.writeNdefMessage(tagMsg); thisNdef.makeReadOnly(); thisNdef.close(); tagHandler.sendEmptyMessage(WRITE_SUCCESS); } } else { tagHandler.sendEmptyMessage(READONLY); } } catch (IOException e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); tagHandler.sendEmptyMessage(IOEXCEPTION); } catch (FormatException e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); e.printStackTrace(); tagHandler.sendEmptyMessage(FORMATEXCEPTION); } } }).start(); }
From source file:st.alr.homA.ActivityQuickpublishNfc.java
private boolean write(String text, Tag tag) { boolean success = true; NdefRecord aar = NdefRecord.createApplicationRecord("st.alr.homA"); NdefRecord[] records = { createRecord(text), aar }; NdefMessage ndefMsg = new NdefMessage(records); try {/*w ww.ja v a 2 s . c o m*/ Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { publishProgress(getResources().getString(R.string.nfcWriteDialogTagReadOnly), false); success = false; } if (ndef.getMaxSize() < ndefMsg.getByteArrayLength()) { publishProgress( getResources().getString(R.string.nfcWriteDialogTagCapacityIs) + ndef.getMaxSize() + " byte" + getResources().getString(R.string.nfcWriteDialogTagMessageSizeIs) + ndefMsg.getByteArrayLength() + "byte.", false); success = false; } ndef.writeNdefMessage(ndefMsg); success = true; } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(ndefMsg); publishProgress(getResources().getString(R.string.nfcWriteDialogTagFormatedAndWrote), true); success = true; } catch (IOException e) { publishProgress(getResources().getString(R.string.nfcWriteDialogTagFailedToFormat), false); success = false; } } else { publishProgress(getResources().getString(R.string.nfcWriteDialogTagNoNDEFSupport), false); success = false; } } } catch (Exception e) { Log.e(this.toString(), getResources().getString(R.string.nfcWriteDialogTagFailedToWrite) + " (" + e.getMessage() + ")", e); } return success; }
From source file:mai.whack.StickyNotesActivity.java
boolean writeTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try {//from w ww . jav a 2 s.co 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:ch.bfh.instacircle.NetworkActiveActivity.java
/** * Writes an NFC Tag/*from www . j a va 2 s.c om*/ * * @param tag * The reference to the tag * @param message * the message which should be writen on the message * @return true if successful, false otherwise */ public boolean writeTag(Tag tag, NdefMessage message) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("InstaCircle - write NFC Tag failed"); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); try { // see if tag is already NDEF formatted Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { Log.d(TAG, "This tag is read only."); alertDialog.setMessage("This tag is read only."); alertDialog.show(); return false; } // work out how much space we need for the data int size = message.toByteArray().length; if (ndef.getMaxSize() < size) { Log.d(TAG, "Tag doesn't have enough free space."); alertDialog.setMessage("Tag doesn't have enough free space."); alertDialog.show(); return false; } ndef.writeNdefMessage(message); Log.d(TAG, "Tag written successfully."); } else { // attempt to format tag NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); Log.d(TAG, "Tag written successfully!"); } catch (IOException e) { alertDialog.setMessage("Unable to format tag to NDEF."); alertDialog.show(); Log.d(TAG, "Unable to format tag to NDEF."); return false; } } else { Log.d(TAG, "Tag doesn't appear to support NDEF format."); alertDialog.setMessage("Tag doesn't appear to support NDEF format."); alertDialog.show(); return false; } } } catch (Exception e) { Log.d(TAG, "Failed to write tag"); return false; } alertDialog.setTitle("InstaCircle"); alertDialog.setMessage("NFC Tag written successfully."); alertDialog.show(); return true; }
From source file:com.piusvelte.taplock.client.core.TapLockSettings.java
@Override protected void onResume() { super.onResume(); Intent intent = getIntent();//from w w w .ja va 2s .co 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(); } } }