通过NDEF发送两个Textfield的内容

时间:2013-02-13 23:40:12

标签: android nfc ndef

我有一个Android应用程序,其中有两个文本字段,名称为Peter Smith,编号为123456.我想通过NFC发送此文件。我的问题在于我只得到名字而不是数字。如果你不介意,你可以看看我的代码,也许我犯了一个小错误,我无法看到。

public class MainActivity extends Activity implements CreateNdefMessageCallback,
        OnNdefPushCompleteCallback {
    NfcAdapter mNfcAdapter;
    TextView beamMsg;
    TextView beamMsg2;
    private static final int MESSAGE_SENT = 1;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        beamMsg = (TextView) findViewById(R.id.msg);
        beamMsg2 = (TextView) findViewById(R.id.msg_ID);
        beamMsg.setText("Peter Smith");
        beamMsg2.setText("123456");

        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            beamMsg = (TextView) findViewById(R.id.msg);
            beamMsg2= (TextView) findViewById(R.id.msg_ID);

            beamMsg.setText("NFC is not available on this device.");
            beamMsg2.setText("NFC is not available on this device.");
        } else {
            // Register callback to set NDEF message
            mNfcAdapter.setNdefPushMessageCallback(this, this);
            // Register callback to listen for message-sent success
            mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
        }
    }

    public void submitClicked(View v)
    {
        Toast toast = Toast.makeText(getApplicationContext(), R.string.info,
                Toast.LENGTH_LONG);
        toast.show();
    }
    /**
     * Implementation for the CreateNdefMessageCallback interface
     */
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                beamMsg.getText()  .toString(), null));

        return msg;

    }

    public NdefMessage createNdefMessage_two(NfcEvent event) {
        NdefMessage msg2 = new NdefMessage(NdefRecord.createMime(
                beamMsg2.getText()  .toString(), null));

        return msg2;

    }




    /**
     * Implementation for the OnNdefPushCompleteCallback interface
     */
    @Override
    public void onNdefPushComplete(NfcEvent arg0) {
        // A handler is needed to send messages to the activity when this
        // callback occurs, because it happens from a binder thread
        mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
    }

    /** This handler receives a message from onNdefPushComplete */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_SENT:
                Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
                break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    void processIntent(Intent intent) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        NdefMessage msg2 = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        beamMsg.setText(new String(msg.getRecords()[0].getPayload()));
        beamMsg2.setText(new String(msg.getRecords()[1].getPayload()));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // If NFC is not available, we won't be needing this menu
        if (mNfcAdapter == null) {
            return super.onCreateOptionsMenu(menu);
        }
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_settings:
                Intent intent = new Intent(Settings.ACTION_NFCSHARING_SETTINGS);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您只需向ndef消息添加一条ndef记录,即createNdefMessage(...)方法。因此,尽管您的代码会读取两条记录,但仍然只发送一条记录。

答案 1 :(得分:0)

对于那些关心的人(因为问题已经过时) 而不是双重createNdefMessage

@Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                beamMsg.getText()  .toString(), null));

        return msg;

    }

    public NdefMessage createNdefMessage_two(NfcEvent event) {
        NdefMessage msg2 = new NdefMessage(NdefRecord.createMime(
                beamMsg2.getText()  .toString(), null));

        return msg2;

    }

只需这样做

@Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        NdefMessage msg = new NdefMessage(
              NdefRecord.createMime(beamMsg.getText().toString(), null), 
              NdefRecord.createMime(beamMsg2.getText().toString(), null)
        );

        return msg;

    }

我希望这有助于某人

答案 2 :(得分:0)

只需将记录与某些内容分开,例如';'接收时修剪?
还有一些NDEF交换的示例代码:

public class MainActivity extends AppCompatActivity implements NfcAdapter.CreateNdefMessageCallback {

private NfcAdapter mNfcAdapter;
TextView tv;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.textViewReceivedMessage);

    NfcManager nfcManager = (NfcManager) getSystemService(NFC_SERVICE);
    mNfcAdapter = nfcManager.getDefaultAdapter();

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

private static NdefMessage getTestMessage() {
    byte[] mimeBytes = "application/com.android.cts.verifier.nfc"
            .getBytes(Charset.forName("US-ASCII"));
    byte[] id = new byte[] {1, 3, 3, 7};
    byte[] payload = "CTS Verifier NDEF Push Tag".getBytes(Charset.forName("US-ASCII"));
    return new NdefMessage(new NdefRecord[] {
            new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, id, payload)
    });
}


@Override
protected void onResume() {
    super.onResume();

    mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
    mNfcAdapter.setNdefPushMessageCallback(this, this);
}

// sending message
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    return getTestMessage();
}


private NdefMessage[] getNdefMessages(Intent intent) {
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (rawMessages != null) {
        NdefMessage[] messages = new NdefMessage[rawMessages.length];
        for (int i = 0; i < messages.length; i++) {
            messages[i] = (NdefMessage) rawMessages[i];
        }
        return messages;
    } else {
        return null;
    }
}

static String displayByteArray(byte[] bytes) {
    String res="";
    StringBuilder builder = new StringBuilder().append("[");
    for (int i = 0; i < bytes.length; i++) {
        res+=(char)bytes[i];
    }
    return res;
}

// displaying message
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    NdefMessage[] messages = getNdefMessages(intent);
    tv.setText(displayByteArray(messages[0].toByteArray()));
}

}