/** Metoda zapisujaca w tle wiadomosc do tagu NFC Przed sprawdzeniem formatuje tag */ @Override protected Void doInBackground(Void... nop) { int size = this.msg.toByteArray().length; try { Ndef ndef = Ndef.get(this.tag); if (ndef == null) { NdefFormatable formatable = NdefFormatable.get(this.tag); if (formatable != null) { try { formatable.connect(); try { formatable.format(this.msg); } catch (Exception e) { this.returnText = R.string.nfc_tag_refused_to_format; } } catch (Exception e) { this.returnText = R.string.nfc_tag_refused_to_connect; } finally { formatable.close(); } } else { this.returnText = R.string.nfc_tag_does_not_support_ndef; } } else { ndef.connect(); try { if (!ndef.isWritable()) { this.returnText = R.string.nfc_tag_is_read_only; } else if (ndef.getMaxSize() < size) { this.returnText = R.string.nfc_message_is_too_big; } else { ndef.writeNdefMessage(this.msg); this.returnText = R.string.nfc_tag_saved; this.returnStatus = Activity.RESULT_OK; } } catch (Exception e) { this.returnText = R.string.nfc_tag_refused_to_connect; } finally { ndef.close(); } } } catch (Exception e) { Log.e(TAG, "Exception when writing tag", e); this.returnText = R.string.nfc_general_exception; } return (null); }
public boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) { int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(detectedTag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_SHORT).show(); return false; } if (ndef.getMaxSize() < size) { Toast.makeText( this, "The data cannot written to tag,Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.", Toast.LENGTH_SHORT) .show(); return false; } ndef.writeNdefMessage(message); ndef.close(); Toast.makeText(this, "Message is written tag.", Toast.LENGTH_SHORT).show(); return true; } else { NdefFormatable ndefFormat = NdefFormatable.get(detectedTag); if (ndefFormat != null) { try { ndefFormat.connect(); ndefFormat.format(message); ndefFormat.close(); Toast.makeText(this, "The data is written to the tag ", Toast.LENGTH_SHORT).show(); return true; } catch (IOException e) { Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show(); return false; } } else { Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show(); return false; } } } catch (Exception e) { Toast.makeText(this, "Write opreation is failed", Toast.LENGTH_SHORT).show(); } return false; }