保存多个NFC标签 - 问题修改教程以保存多个NDef记录

时间:2013-03-31 01:25:23

标签: android nfc

我正在遵循一个允许用户将数据保存到NFC标签的教程。我正在尝试修改教程源代码以包含第二个EditText字段并保存第二个标记但是如果我注释掉以下行,我只能保存第二个NDef记录:

// write(message.getText()。toString(),mytag);

我需要能够写两个标签:

write(message.getText().toString(),mytag);

write(message.getText().toString(),mytag2); 

...但我需要帮助将它们连接在一起。

有一个示例显示如何在此处添加多个标记:

https://code.google.com/p/nfc-eclipse-plugin/source/browse/nfc-eclipse-plugin/src/android/nfc16/NdefMessage.java

但是我需要帮助格式化当前的源以反映此方法。 (每当我尝试时,我最终会在日志中出现其他问题或强制关闭问题。)

提前致谢!

JAVA:

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "ParserError", "ParserError" })
public class MainActivity extends Activity{

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

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

        ctx=this;
        Button btnWrite = (Button) findViewById(R.id.button);
        final TextView message = (TextView)findViewById(R.id.edit_message);

        ctx2=this;
        final TextView message2 = (TextView)findViewById(R.id.edit_message2);


        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();

                    if(mytag2==null){
                        Toast.makeText(ctx2, ctx2.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
                        }
                    }else{
                        // write(message.getText().toString(),mytag);
                        write(message.getText().toString(),mytag2);
                        Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
                        Toast.makeText(ctx2, ctx2.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();
                    Toast.makeText(ctx2, ctx2.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();
                    Toast.makeText(ctx2, ctx2.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);


        // SUGGESTED IMPLEMENTATION
        //  mRecords = new NdefRecord[1 + records.length];
           // mRecords[0] = record;
           // System.arraycopy(records, 0, mRecords, 1, records.length);





        // 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);   
            mytag2 = 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:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Please Enter Your Password: ">
    </TextView>



         <EditText
            android:id="@+id/edit_message2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="SSID" />



     <EditText
            android:id="@+id/edit_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="WiFi Password" />

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

</LinearLayout>

教程源代码(显示上面的源代码实现只保存了一条NDef记录 - 我修改了它以保存两条NDef记录)

http://www.framentos.com/en/android-tutorial/2012/07/31/write-hello-world-into-a-nfc-tag-with-a/

1 个答案:

答案 0 :(得分:0)

注释掉这一行:

write(message.getText().toString(),mytag);

我认为它会起作用。

我认为问题是write()方法只能写入一个标记,并且在调用第二个write()方法时,标记仍然被第一个write()方法锁定。如果我是你,我会尝试在write()定义的定义中添加第二个字段,或者如果这不可能,我会尝试将两个字段的文本连接在一起,并在两个字段的中间连接一个标记。

另外,要制作这个正确的代码,我会使用AsyncTask在自己的线程内部执行nfc部分,以确保它不会阻止UI线程。我理解为什么编写教程的人没有这样做,这会使他的教程比他想要的复杂得多,但是做nfc是你应该远离UI线程的东西。

关于你的第二个问题:

这可能会这样做:

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

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

当然,这意味着你必须以这种方式调用它(因为它现在还有一个参数):

write(message.getText().toString(), message2.getText().toString(), mytag2);