如何停止改写为NFC标签使用的是Android [英] How to stop overwrite to an NFC tag using Android

查看:384
本文介绍了如何停止改写为NFC标签使用的是Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用卡模拟模式作为一个NFC标签PN512和正在开发Android应用程序读取和写入标签。问题是,只要标签是在NFC领域,该计划将继续读取和写入标签,但我想从覆盖相同的标签,一旦成功writen停止程序。是否有任何的解决方案是什么?

(我知道有没有办法基于Android SDK以编程方式禁用NFC)

  @覆盖
公共无效的onCreate(捆绑savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    BTN =(按钮)findViewById(R.id.btn_OK);
    mEditText =(EditText上)findViewById(R.id.text_username);
    btn.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            preFS = getShared preferences(prefName,MODE_PRIVATE);
            共享preferences.Editor编辑器= prefs.edit();
            editor.putString(TEXT_VALUE_KEY,mEditText.getText()的toString());
            editor.commit();            字符串outtxt =请点击并按住电话标记;
            吐司toastedit12 = Toast.makeText(getApplicationContext(),outtxt,Toast.LENGTH_SHORT);
            toastedit12.show();
        }
    });    resolveIntent(getIntent());
}
//当读取标签这种方法/执行任务
无效resolveIntent(意向意图)
{
    NdefMessage MSG1,MSG2;
    //解析意图
    字符串行动= intent.getAction();    如果(NfcAdapter.ACTION_TAG_DISCOVERED.equals(动作)||
        NfcAdapter.ACTION_NDEF_DISCOVERED.equals(动作)){        尝试
        {
            mRecord = createRecord();
        }
        赶上(例外五)
        {
            吐司toaste = Toast.makeText(getApplicationContext(),异常呼叫创造记录,Toast.LENGTH_SHORT);
            toaste.show();
        }        //当标签被发现,我们将其发送到服务是保存。我们
        //包括服务回拨到的PendingIntent。这个
        //将导致此活动与onNewIntent重新启动()。在
        //那个时候,我们从数据库中读取并进行查看。
       Parcelable [] = rawMsgs intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
       NdefMessage []封邮件;       如果(rawMsgs!= NULL)
       {
            封邮件=新NdefMessage [rawMsgs.length]
            的for(int i = 0; I< rawMsgs.length;我++)
            {
                封邮件[I] =(NdefMessage)rawMsgs [I]
            }            MSG1 =封邮件[0];
            myPayload = msg1.getRecords()[0] .getPayload();
        }
        其他{
            //未知的标签类型
            字节[] =空新的字节[] {};
            NdefRecord纪录=新NdefRecord(NdefRecord.TNF_UNKNOWN,空,空,空);
            MSG 2 =新NdefMessage(新NdefRecord [] {录音});
            封邮件=新NdefMessage [] {} MSG2;
        }
        writeToNfcTag(意向);
    }
    公共NdefRecord createRecord()抛出UnsupportedEncodingException {
        共享preferences preFS = getShared preferences(prefName,MODE_PRIVATE);
        mEditText.setText(prefs.getString(TEXT_VALUE_KEY,高清))        字符串LANG =EN;        。字节[] = textBytes mEditText.getText()的toString()的getBytes();        字节[] = langBytes lang.getBytes(US-ASCII);
        INT langLength = langBytes.length;
        // INT myPayloadLength = myPayload.length;
        INT正文长度= textBytes.length;
        字节[] =有效载荷新的字节[1 + langLength +正文长度]        //设置状态字节(见实际位数NDEF规范)
        有效载荷[0] =(字节)langLength;        //复制langbytes和textbytes到有效载荷
        System.arraycopy(langBytes,0,有效载荷,1,langLength);
        System.arraycopy(textBytes,0,有效载荷,l + langLength,正文长度);
        NdefRecord纪录=新NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                                           NdefRecord.RTD_TEXT,
                                           新的字节[0]
                                           负载);
        返回记录;
    }
    公共无效writeToNfcTag(意向意图)
    {
        标签标签= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        尝试
        {
            写(标签);
        }
        赶上(例外五)
        {
            //这个吐司;保释
        }
    }
    公共无效写入(标签标签)抛出IOException异常,FormatException {
        NdefRecord [] =记录{mRecord};
        NdefMessage消息=新NdefMessage(记录);        //获取NDEF的实例为标签。
        NDEF NDEF = Ndef.get(标签);        //启用I / O
        ndef.connect();        //写消息
        ndef.writeNdefMessage(消息);        //关闭连接
        ndef.close();        意向myIntent = NULL;
        myIntent =新意图(MyAndroidAppActivity.this,TagDeactivatedActivity.class);        myIntent.setFlags(myIntent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
        完();
    }
}


解决方案

在您在标签写入你能做到这一点,但请记住,这个过程是不可逆的。

  NDEF NDEF = Ndef.get(标签);
    如果(NDEF!= NULL){
        ndef.makeReadOnly();
    }

I'm using PN512 in card emulation mode as a NFC tag and am developing an Android application to read and write into the tag. The problem is, as long as the tag is in the NFC field, the program will keep reading and writing to the tag, but I want stop the program from overwriting the same tag once successfully writen. Are there any solutions for that?

(I know there is no way to programmatically disable NFC based on Android SDK)

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

    btn = (Button) findViewById(R.id.btn_OK);
    mEditText = (EditText) findViewById(R.id.text_username);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(TEXT_VALUE_KEY, mEditText.getText().toString());
            editor.commit();

            String outtxt = "please touch and hold phone to tag";
            Toast toastedit12 = Toast.makeText(getApplicationContext(), outtxt, Toast.LENGTH_SHORT);
            toastedit12.show();
        }
    });

    resolveIntent(getIntent());
}


// This method/task executes when the tag is read
void resolveIntent(Intent intent)
{
    NdefMessage msg1, msg2;
    // Parse the intent
    String action = intent.getAction();

    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) ||
        NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

        try
        {
            mRecord=createRecord();
        }
        catch (Exception e)
        {
            Toast toaste = Toast.makeText(getApplicationContext(), "exception in call to create record", Toast.LENGTH_SHORT);
            toaste.show();
        }

        // When a tag is discovered we send it to the service to be save. We
        // include a PendingIntent for the service to call back onto. This
        // will cause this activity to be restarted with onNewIntent(). At
        // that time we read it from the database and view it.
       Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
       NdefMessage[] msgs;

       if (rawMsgs != null)
       {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }

            msg1 = msgs[0];
            myPayload=msg1.getRecords()[0].getPayload();
        }
        else {
            // Unknown tag type
            byte[] empty = new byte[] {};
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            msg2 = new NdefMessage(new NdefRecord[] {record});
            msgs = new NdefMessage[] {msg2};
        }
        writeToNfcTag(intent);
    }


    public NdefRecord createRecord() throws UnsupportedEncodingException {
        SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        mEditText.setText(prefs.getString(TEXT_VALUE_KEY, "def"))

        String lang       = "en";

        byte[] textBytes  = mEditText.getText().toString().getBytes();

        byte[] langBytes  = lang.getBytes("US-ASCII");
        int    langLength = langBytes.length;
        //int    myPayloadLength = myPayload.length;
        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
        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);
        return record;
    }


    public void writeToNfcTag(Intent intent)
    {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        try
        {
            write(tag);
        }
        catch (Exception e)
        {
            // Toast this; bail
        }
    }


    public void write(Tag tag) throws IOException, FormatException {
        NdefRecord[] records = { mRecord };
        NdefMessage  message = new NdefMessage(records);

        // Get an instance of Ndef for the tag.
        Ndef ndef = Ndef.get(tag);

        // Enable I/O
        ndef.connect();

        // Write the message
        ndef.writeNdefMessage(message);

        // Close the connection
        ndef.close();

        Intent myIntent = null;
        myIntent = new Intent(MyAndroidAppActivity.this, TagDeactivatedActivity.class);

        myIntent.setFlags(myIntent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
        finish();
    }
}

解决方案

After you write in the tag you can do this but keep in mind that this process is not reversible.

    Ndef ndef = Ndef.get(tag);  
    if (ndef != null) { 
        ndef.makeReadOnly();
    }

这篇关于如何停止改写为NFC标签使用的是Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆