2

是否可以读取然后写入,然后再次读取我们之前在 NFC 标签上写入的相同数据,而无需将其从 Android 中的字段(移动设备)中删除?如果有人做过,请在这里分享....

public class MainActivity extends Activity
{
    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    Tag mytag;
    private TextView mTextViewData;
    Context ctx;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ctx=this;

        mTextViewData = (TextView)findViewById(R.id.mtextView);

        Button btnWrite = (Button) findViewById(R.id.write_button);
        final EditText mEditText = (EditText)findViewById(R.id.edit_message);

        adapter = NfcAdapter.getDefaultAdapter(this);

        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        IntentFilter tagDetected1 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

        try 
        {
            tagDetected1.addDataType("text/nfc-service-tag");
        } 
        catch (MalformedMimeTypeException e) 
        {
            throw new RuntimeException("Could not add MIME type.", e);
        }
        writeTagFilters = new IntentFilter[] { tagDetected1 };

        btnWrite.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {

                    if(mytag==null)
                    {
                        Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
                    }
                    else
                    {
                        writeTag(mEditText.getText().toString(),mytag);

                    }

            }
        });

    }

    private void writeTag(String text,Tag tag) 
    {
        // record to launch Play Store if app is not installed
        // record that contains our custom "retro console" game data, using custom MIME_TYPE
        String mimeType = "text/nfc-service-tag";
        byte[] payload = text.getBytes(Charset.forName("US-ASCII"));
        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
        NdefMessage message = new NdefMessage(new NdefRecord[] { record });
        try 
        {
            // see if tag is already NDEF formatted
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) 
            {
                ndef.connect();
                if (!ndef.isWritable())
                {
                    Toast.makeText(ctx, "Read-only tag.", Toast.LENGTH_LONG ).show();
                }
                // work out how much space we need for the data
                int size = message.toByteArray().length;
                if (ndef.getMaxSize() < size) 
                {
                    Toast.makeText(ctx, "Tag doesn't have enough free space.", Toast.LENGTH_LONG).show();
                }
                ndef.writeNdefMessage(message);
                Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
                ndef.close();
            } 
            else 
            {
                // attempt to format tag
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) 
                {
                    try 
                    {
                        format.connect();
                        format.format(message);
                        Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
                    } 
                    catch (IOException e) 
                    {
                        Toast.makeText(ctx,"Unable to format tag to NDEF.", Toast.LENGTH_LONG).show();
                    }
                }
                else 
                {
                    Toast.makeText(ctx,"Tag doesn't appear to support NDEF format.", Toast.LENGTH_LONG).show();
                }
            }
        }
        catch(Exception e)
        {

        }
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        String action = intent.getAction();
        if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            NdefMessage[] msgs = getNdefMessagesFromIntent(intent);
            final NdefMessage msg = (NdefMessage)msgs[0];
            String payload = new String(msg.getRecords()[0].getPayload());
            mTextViewData.setText(payload);

            mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);    

            Toast.makeText(this, "In onNewIntent()", Toast.LENGTH_LONG ).show();
        }

        else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) 
        {
            Toast.makeText(this, "This NFC tag has no NDEF data.", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if (getIntent().getAction() != null) 
        {
            // tag received when app is not running and not in the foreground:
            if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) 
            {
                NdefMessage[] msgs = getNdefMessagesFromIntent(getIntent());
                NdefRecord record = msgs[0].getRecords()[0];
                byte[] payload = record.getPayload();

                String payloadString = new String(payload);
                mTextViewData.setText(payloadString);

                Toast.makeText(this, "In onResume()", Toast.LENGTH_LONG ).show();

            }
        }
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        adapter.disableForegroundDispatch(this);
    }

    NdefMessage[] getNdefMessagesFromIntent(Intent intent) 
    {
        // Parse the intent
        NdefMessage[] msgs = null;
        String action = intent.getAction();
        if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) 
        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            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[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
        } 
        else 
        {
            //Log.e(TAG, "Unknown intent.");
            finish();
        }
        return msgs;
    }    
}
4

1 回答 1

3

您可以ndef.getNdefMessage()在完成后立即致电ndef.writeNdefMessage(message)检查结果。它实际上会从标签中读回 NDEF 消息。但是,一般情况下,当ndef.writeNdefMessage(message)不抛出异常时,可以安全地假设消息写入成功。

于 2013-02-04T08:30:00.333 回答