Android的NFC读取标签 [英] Android NFC Reading a Tag

查看:261
本文介绍了Android的NFC读取标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的申请,我有两个选择:编写和读取NFC标签。我在做所谓的WriteNFC另一个活动NFC标签写入过程。我想我的主要活动读取并显示标签数据,当标签进入范围。写作过程中似乎是好。但每当我试图读取标签。它显示什么。

 公共类MainActivity延伸活动{公共静态INT ID = 1;
公共静态INT bakiye = 5;
公共静态语境myContext;
公共静态布尔availableForRead = TRUE;
私人按钮myButton的;保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    则myButton =(按钮)findViewById(R.id.button1);    myButton.setOnClickListener(新View.OnClickListener(){        公共无效的onClick(查看为arg0){            意图I =新意图(getApplicationContext(),nfcWrite.class);
            startActivity(ⅰ);        }
    });}@覆盖
保护无效onResume(){
    // TODO自动生成方法存根
    super.onResume();}@覆盖
保护无效onNewIntent(意向意图){    的System.out.println(意图检测);
    如果(intent.getType()= NULL和放大器;!&安培; intent.getType()等于(应用程序/+ getPackageName())){
        //读取包含NFC数据的第一条记录
        Parcelable [] = rawMsgs intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefRecord relayRecord =((NdefMessage)rawMsgs [0])getRecords()[0];
        字符串nfcData =新的String(relayRecord.getPayload());
        的System.out.println(阅读过程完成...);        //显示标签上的数据
        Toast.makeText(这一点,nfcData,Toast.LENGTH_SHORT).show();    }}

}

这是我的nfcWrite活动:

 包com.example.nfchandler;
进口java.io.IOException异常;
进口java.nio.charset.Charset中;进口android.app.Activity;
进口android.app.PendingIntent;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.nfc.FormatException;
进口android.nfc.NdefMessage;
进口android.nfc.NdefRecord;
进口android.nfc.NfcAdapter;
进口android.nfc.Tag;
进口android.nfc.TagLostException;
进口android.nfc.tech.Ndef;
进口android.nfc.tech.NdefFormatable;
进口android.os.Bundle;
进口android.widget.Toast;公共类nfcWrite延伸活动{    私人INT ID = 1;
    私人INT余额= 5;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.nfc_write);
    }    @覆盖
    保护无效onNewIntent(意向意图){
        // TODO自动生成方法存根
        super.onNewIntent(意向);
         标签标签= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            串nfcMessage = intent.getStringExtra(nfcMessage);            如果(nfcMessage!= NULL){
                writeTag(这一点,标签,nfcMessage);
            }
    }    @覆盖
    保护无效onResume(){
        // TODO自动生成方法存根
        super.onResume();
        setupIntent();
    }    公共无效setupIntent(){
        字符串nfcMessage = ID + - +平衡;        //当一个NFC标签进入范围内,调用的主要活动这
        //处理数据写入标签
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(本);        意图nfcIntent =新意图(这一点,nfcWrite.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        nfcIntent.putExtra(nfcMessage,nfcMessage);
        PI的PendingIntent = PendingIntent.getActivity(这一点,0,nfcIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        IntentFilter的tagDetected =新的IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);        nfcAdapter.enableForegroundDispatch((活动)这一点,PI,新的IntentFilter [] {} tagDetected,NULL);
    }    公共布尔writeTag(上下文的背景下,标签标签,字符串数据){
        //记录发起Play商店,如果没有安装的应用程序
        NdefRecord AP precord = NdefRecord.createApplicationRecord(context.getPackageName());        //与我们关心的实际数据记录
        NdefRecord relayRecord =新NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                新的String(应用程序/+ context.getPackageName())。的getBytes(Charset.forName(US-ASCII))
                空,data.getBytes());        //既记录完整NDEF消息
        NdefMessage消息=新NdefMessage(新NdefRecord [] {relayRecord,AP precord});        尝试{
            //如果标签已经格式化,只写邮件给它
            NDEF NDEF = Ndef.get(标签);
            如果(NDEF!= NULL){
                ndef.connect();                //确保标签是可写的
                如果(!ndef.isWritable()){
                    Toast.makeText(getApplicationContext(),ETIKETyazılabilirdeğil,Toast.LENGTH_SHORT).show();
                    返回false;
                }                //检查是否有对消息的标记足够的空间
                。INT大小= message.toByteArray()长;
                如果(ndef.getMaxSize()<大小){
                    Toast.makeText(getApplicationContext(),Etikette yeterli阿兰郁慕明...,Toast.LENGTH_SHORT).show();
                    返回false;
                }                尝试{
                    //将数据写入标签
                    ndef.writeNdefMessage(消息);                    Toast.makeText(getApplicationContext(),信息酒店yazmabaşarılı...,Toast.LENGTH_SHORT).show();                    返回true;
                }赶上(TagLostException TLE){
                    返回false;
                }赶上(IOException异常IOE){
                    返回false;
                }赶上(FormatException FE){
                    返回false;
                }
                //如果标签没有被格式化,与消息格式化
            }其他{
                NdefFormatable格式= NdefFormatable.get(标签);
                如果(格式!= NULL){
                    尝试{
                        format.connect();
                        format.format(消息);                        返回true;
                    }赶上(TagLostException TLE){
                        返回false;
                    }赶上(IOException异常IOE){                        返回false;
                    }赶上(FormatException FE){                        返回false;
                    }
                }其他{                    返回false;
                }
            }
        }赶上(例外五){        }        返回false;
    }}


解决方案

继code解决我的问题:

 意向意图= getIntent();    NdefMessage []封邮件;
     如果(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent()。的getAction())){
            Parcelable [] = rawMsgs intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefRecord relayRecord =((NdefMessage)rawMsgs [0])getRecords()[0];
            字符串nfcData =新的String(relayRecord.getPayload());
            Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
        }

In my application, I got two options : Writing and Reading a NFC tag. I am doing NFC Tag Writing process in another activity called WriteNFC. I want my main activity reads and displays tag data, when the tag comes into range. Writing process seem to be ok. But whenever i try to read the tag. It displays nothing.

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

    }

}

}

And here is my nfcWrite activity:

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

}

解决方案

Following code solved my problem:

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

这篇关于Android的NFC读取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆