如何在android中将多个字符串写入NFC标记

如何在android中将多个字符串写入NFC标记,android,nfc,Android,Nfc,我是android新手,我正在尝试使用单独的edittext字段在nfc标记中编写六个单独的字符串。当我运行应用程序时。我试着同时写六个字符串。。写了之后,在读标签时,我只能看到丢失的字符串。我怎样才能分别看到所有的弦呢。。 下面是我的代码 public class MainActivity extends Activity{ NfcAdapter adapter; PendingIntent pendingIntent; IntentFilter writeTagFi

我是android新手,我正在尝试使用单独的edittext字段在nfc标记中编写六个单独的字符串。当我运行应用程序时。我试着同时写六个字符串。。写了之后,在读标签时,我只能看到丢失的字符串。我怎样才能分别看到所有的弦呢。。 下面是我的代码

public class MainActivity extends Activity{

    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    boolean writeMode;
    Tag mytag;
    Context ctx;

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

        ctx=this;
        Button btnWrite = (Button) findViewById(R.id.button);
        final TextView plateno = (TextView)findViewById(R.id.plate_no);
        final TextView model = (TextView)findViewById(R.id.model);
        final TextView chasis = (TextView)findViewById(R.id.chasis_no);
        final TextView engine = (TextView)findViewById(R.id.engine_no);
        final TextView duedate = (TextView)findViewById(R.id.due_date);
        final TextView rotexno = (TextView)findViewById(R.id.rotex_no);

        btnWrite.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                try {
                    if(mytag==null){
                        Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
                    }else{
                        write(plateno.getText().toString(),mytag);
                        write(model.getText().toString(),mytag);
                        write(chasis.getText().toString(),mytag);
                        write(engine.getText().toString(),mytag);
                        write(duedate.getText().toString(),mytag);
                        write(rotexno.getText().toString(),mytag);
                        Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(ctx, ctx.getString(R.string.error_writing), Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                } catch (FormatException e) {
                    Toast.makeText(ctx, ctx.getString(R.string.error_writing) , Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                }
            }
        });

        adapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };

    }



    private void write(String text, Tag tag) throws IOException, FormatException {

        NdefRecord[] records = { createRecord(text) };
        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();
    }



    private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
        String lang       = "en";
        byte[] textBytes  = text.getBytes();
        byte[] langBytes  = lang.getBytes("US-ASCII");
        int    langLength = langBytes.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 recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,  NdefRecord.RTD_TEXT,  new byte[0], payload);

        return recordNFC;
    }


    @Override
    protected void onNewIntent(Intent intent){
        if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);    
            Toast.makeText(this, this.getString(R.string.ok_detection) + mytag.toString(), Toast.LENGTH_LONG ).show();
        }
    }

    @Override
    public void onPause(){
        super.onPause();
        WriteModeOff();
    }

    @Override
    public void onResume(){
        super.onResume();
        WriteModeOn();
    }

    private void WriteModeOn(){
        writeMode = true;
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    private void WriteModeOff(){
        writeMode = false;
        adapter.disableForegroundDispatch(this);
    }


}
布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write you message: ">
    </TextView>

        <EditText
            android:id="@+id/plate_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="PlateNumber" />
         <EditText
            android:id="@+id/model"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Model" />
          <EditText
            android:id="@+id/chasis_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Chasis Number" />
           <EditText
            android:id="@+id/engine_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Engine Number" />
            <EditText
            android:id="@+id/due_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Due Date" />
            <EditText
            android:id="@+id/rotex_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Rotex Number" />

 <Button
     android:id="@+id/button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:layout_weight="1"
     android:text="Write!!" />

</LinearLayout>

对于试图存储在NFC标记上的每个字符串,分别使用函数write()。在write()函数中,您仅使用该字符串创建NDEFmessage,并将该消息存储到标记中

这意味着每次调用write()时,都会用新的NDEFmessage覆盖以前的NDEFmessage。结果是您只能看到标记上的最后一个字符串

要在标记上存储多个字符串(前提是标记内存足够大),需要将所有字符串放入一个NDEFmessage中,并将该消息存储到标记中

这意味着您应该为每个字符串创建一个NDEFrecord(例如,通过createTextRecord(string languageCode,string text))并将它们全部放入记录中。现在,当您创建NDEFmessage时,所有字符串都包含在NDEFmessage中