Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

android - Use NFC "payload" variable in "if" statement

I'm attempting to use the "payload" value from an external record that I've written to an NFC tag. I know that the record has been written successfully to the NFC tag. I'm having problems using that "payload" value in an "if" statement. My code follows:

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

    // read nfc tag...IS THIS WHAT WILL "READ" THE PAYLOAD VALUE THAT HAS BEEN WRITTIEN?

    if (getIntent().hasExtra(NfcAdapter.EXTRA_TAG)) {

        NdefMessage ndefMessage =       this.getNdefMessageFromIntent(getIntent());
        if(ndefMessage.getRecords().length > 0){
            NdefRecord ndefRecord = ndefMessage.getRecords()[0];
            String payload = new String(ndefRecord.getPayload());
            Toast.makeText(this, payload, Toast.LENGTH_SHORT).show();
        }
    }
    enableForegroundDispatchSystem();
}

Once I'm able to "read" the payload value, I want to specify what block of code to run. For example:

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);


    ///IF Payload Value = 1...Then run this code block:

    if (intent.hasExtra(NfcAdapter.EXTRA_TAG))
    {
        Toast.makeText(this, "NFC Scan", Toast.LENGTH_SHORT).show();
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String url = "http://www.google.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }

    ///IF Payload = 2, then run this code block: 

 if (intent.hasExtra(NfcAdapter.EXTRA_TAG))
    {
        Toast.makeText(this, "NFC Scan", Toast.LENGTH_SHORT).show();
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String url = "http://www.yahoo.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }

}

I hope this makes sense, I'm only trying to run a simple "if/else" statement based on the value of the Payload that has been written to the tag. Thanks for any help!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you refer to the String variable payload in OnResume, then you can write:

if (payload.equals("1")) {...}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...