0

我正在关注一个允许用户将数据保存到 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

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

提前致谢!

爪哇:

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/

4

1 回答 1

0

注释掉这一行:

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

我认为它会起作用。

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

Also to make this proper code, I'd do the nfc part inside its own thread using AsyncTask to make sure it doesn't block the UI thread. I understand why the guy writing the tutorial didn't do that, that would have made his tutorial much more complicated than he wanted to, but doing nfc is something you should be keeping out of the UI thread.

Regarding your second question:

This might do it:

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

and of course, this means you'll have to call it this way (since it now has one more argument):

write(message.getText().toString(), message2.getText().toString(), mytag2);
于 2013-03-31T01:59:49.423 回答