Android NFC阅读标签

时间:2014-04-24 14:58:16

标签: android nfc

在我的应用程序中,我有两个选择:编写和读取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;
    }

}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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

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