Example usage for android.nfc.tech NdefFormatable get

List of usage examples for android.nfc.tech NdefFormatable get

Introduction

In this page you can find the example usage for android.nfc.tech NdefFormatable get.

Prototype

public static NdefFormatable get(Tag tag) 

Source Link

Document

Get an instance of NdefFormatable for the given tag.

Usage

From source file:Main.java

public static boolean writeNFCTag(NdefMessage message, Tag tag) {
    int size = message.toByteArray().length;
    try {/* w w  w  .j  a  v a2  s . c o  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:de.berlin.magun.nfcmime.core.RfidDAO.java

/**
 * @param tag Tag
 * @return true, if the Tag is NDEF formatable.
 */
public boolean isNdefFormatable(Tag tag) {
    return (NdefFormatable.get(tag) != null);
}

From source file:com.macleod2486.androidswissknife.components.NFCCallback.java

@Override
public void onTagDiscovered(Tag tag) {

    EditText tagResult = activity.findViewById(R.id.textEntry);

    try {/*from w w w .  jav a 2s  .  c om*/
        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:jp.co.brilliantservice.android.writertduri.HomeActivity.java

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    String action = intent.getAction();
    if (TextUtils.isEmpty(action))
        return;//from   www  .  j av  a  2  s .c o m

    if (!action.equals(NfcAdapter.ACTION_TECH_DISCOVERED))
        return;

    // NdefMessage?
    String uri = "http://www.brilliantservice.co.jp/";
    NdefMessage message = createUriMessage(uri);

    // ??????????
    Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    List<String> techList = Arrays.asList(tag.getTechList());
    if (techList.contains(Ndef.class.getName())) {
        Ndef ndef = Ndef.get(tag);
        writeNdefToNdefTag(ndef, message);

        Toast.makeText(getApplicationContext(), "wrote NDEF to NDEF tag", Toast.LENGTH_SHORT).show();
    } else if (techList.contains(NdefFormatable.class.getName())) {
        NdefFormatable ndef = NdefFormatable.get(tag);
        writeNdefToNdefFormatable(ndef, message);

        Toast.makeText(getApplicationContext(), "wrote NDEF to NDEFFormatable tag", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "NDEF Not Supported", Toast.LENGTH_SHORT).show();
    }
}

From source file:jp.co.brilliantservice.android.writertdtext.HomeActivity.java

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    String action = intent.getAction();
    if (TextUtils.isEmpty(action))
        return;/*from   w  w  w .  j a v a  2 s.co  m*/

    if (!action.equals(NfcAdapter.ACTION_TECH_DISCOVERED))
        return;

    // NdefMessage?
    String languageCode = "en";
    String text = String.format("Hello, World.(%s)", DATE_FORMAT.format(System.currentTimeMillis()));
    NdefMessage message = createTextMessage(text, languageCode);

    // ??????????
    Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    List<String> techList = Arrays.asList(tag.getTechList());
    if (techList.contains(Ndef.class.getName())) {
        Ndef ndef = Ndef.get(tag);
        writeNdefToNdefTag(ndef, message);

        Toast.makeText(getApplicationContext(), "wrote NDEF to NDEF tag", Toast.LENGTH_SHORT).show();
    } else if (techList.contains(NdefFormatable.class.getName())) {
        NdefFormatable ndef = NdefFormatable.get(tag);
        writeNdefToNdefFormatable(ndef, message);

        Toast.makeText(getApplicationContext(), "wrote NDEF to NDEFFormatable tag", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "NDEF Not Supported", Toast.LENGTH_SHORT).show();
    }
}

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);//  www.  jav a 2s . c  o  m

    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: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 {// ww w  .  j  av  a  2 s.  co  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: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 {/* w w w .j a v  a2 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

/**
 * Formats an NDEF formatable RFID transponder, so NDEF messages can be written to it.
 * @param tag Tag/*from   w  w w. j  av a 2 s  . c  o  m*/
 */
public void formatNdef(Tag tag) {
    // check if Tag is NDEF formattable. If it is, NDEF-format it
    if (NdefFormatable.get(tag) != null) {
        // use NdefSingleton for I/O operations
        NdefSingleton.getInstance().setNdefFormatable(NdefFormatable.get(tag));
        FormatThread ft = new FormatThread();
        ft.run();
    }
}

From source file:mai.whack.StickyNotesActivity.java

boolean writeTag(NdefMessage message, Tag tag) {
    int size = message.toByteArray().length;

    try {/*ww  w. ja v 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;
}