繁体   English   中英

Android NFC读取标签

[英]Android NFC Reading a Tag

在我的应用程序中,我有两个选择:编写和读取NFC标签。 我正在另一个称为WriteNFC的活动中进行NFC标签编写过程。 我希望我的主要活动在标签进入范围时读取并显示标签数据。 编写过程似乎还可以。 但是每当我尝试读取标签时。 它什么也不显示。

public class MainActivity extends Activity {

public static int id = 1;
public static int bakiye = 5;
public static Context myContext;
public static boolean availableForRead = true;
private Button myButton;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myButton = (Button) findViewById(R.id.button1);

    myButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            Intent i = new Intent(getApplicationContext(), nfcWrite.class);
            startActivity(i);

        }
    });

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

}

@Override
protected void onNewIntent(Intent intent) {

    System.out.println("Intent detected");
    if (intent.getType() != null && intent.getType().equals("application/" + getPackageName())) {
        // Read the first record which contains the NFC data
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefRecord relayRecord = ((NdefMessage) rawMsgs[0]).getRecords()[0];
        String nfcData = new String(relayRecord.getPayload());
        System.out.println("Reading Process is Complete...");

        // Display the data on the tag
        Toast.makeText(this, nfcData, Toast.LENGTH_SHORT).show();

    }

}

}

这是我的nfcWrite活动:

package com.example.nfchandler;
import java.io.IOException;
import java.nio.charset.Charset;

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.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.widget.Toast;

public class nfcWrite extends Activity {

    private int id = 1;
    private int balance = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfc_write);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
         Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            String nfcMessage = intent.getStringExtra("nfcMessage");

            if(nfcMessage != null) {
                writeTag(this, tag, nfcMessage);
            }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        setupIntent();
    }

    public void setupIntent() {
        String nfcMessage = id + "-" + balance;

        // When an NFC tag comes into range, call the main activity which
        // handles writing the data to the tag
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        Intent nfcIntent = new Intent(this, nfcWrite.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        nfcIntent.putExtra("nfcMessage", nfcMessage);
        PendingIntent pi = PendingIntent.getActivity(this, 0, nfcIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        nfcAdapter.enableForegroundDispatch((Activity) this, pi, new IntentFilter[] { tagDetected }, null);
    }

    public boolean writeTag(Context context, Tag tag, String data) {
        // Record to launch Play Store if app is not installed
        NdefRecord appRecord = NdefRecord.createApplicationRecord(context.getPackageName());

        // Record with actual data we care about
        NdefRecord relayRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                new String("application/" + context.getPackageName()).getBytes(Charset.forName("US-ASCII")),
                null, data.getBytes());

        // Complete NDEF message with both records
        NdefMessage message = new NdefMessage(new NdefRecord[] { relayRecord, appRecord });

        try {
            // If the tag is already formatted, just write the message to it
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();

                // Make sure the tag is writable
                if (!ndef.isWritable()) {
                    Toast.makeText(getApplicationContext(), "Etiket yazılabilir değil", Toast.LENGTH_SHORT).show();
                    return false;
                }

                // Check if there's enough space on the tag for the message
                int size = message.toByteArray().length;
                if (ndef.getMaxSize() < size) {
                    Toast.makeText(getApplicationContext(), "Etikette yeterli alan yok...", Toast.LENGTH_SHORT).show();
                    return false;
                }

                try {
                    // Write the data to the tag
                    ndef.writeNdefMessage(message);

                    Toast.makeText(getApplicationContext(), "Bilgileri yazma başarılı...", Toast.LENGTH_SHORT).show();

                    return true;
                } catch (TagLostException tle) {
                    return false;
                } catch (IOException ioe) {
                    return false;
                } catch (FormatException fe) {
                    return false;
                }
                // If the tag is not formatted, format it with the message
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);

                        return true;
                    } catch (TagLostException tle) {
                        return false;
                    } catch (IOException ioe) {

                        return false;
                    } catch (FormatException fe) {

                        return false;
                    }
                } else {

                    return false;
                }
            }
        } catch (Exception e) {

        }

        return false;
    }

}

以下代码解决了我的问题:

Intent intent=getIntent();

    NdefMessage[] msgs;
     if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefRecord relayRecord = ((NdefMessage)rawMsgs[0]).getRecords()[0];
            String nfcData = new String(relayRecord.getPayload());
            Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
        }

您的代码有几个有关NFC功能的问题:

  1. 在您的阅读活动中,您仅在onNewIntent方法中检查与NFC相关的意图。 但是,仅在某些条件下才调用onNewIntent方法。 例如,在您的活动开始时不会调用它(例如,由于清单中的意图过滤器触发了它)。 在这种情况下,您将需要在onCreateonStartonResume处理收到的意图。 即使当你扫描标签您的活动已经可见, onNewIntent如果你的活动被标记为将仅singleTop 在这种情况下(当您希望在活动处于前台时在检测到标签时收到通知时,最好注册NFC前台调度。

  2. 在写活动中,您可以通过onResume方法注册NFC前台调度系统。 但是,您不会在onPause释放前台调度。 尽管这将在最新的Android版本(4.4+?)中起作用,但这会导致较旧的Android版本出现严重问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM