Android uses mobile phone NFC to read NFC tag data

Nfc filter tag settings

1 Add permissions in the Manifest:

Add the permission to use nfc in xml

1

<uses-permission android:name="android.permission.NFC" />

<uses-permission android:name="android.permission.NFC" />

This is to restrict installation permissions, only for mobile phones with nfc function (optional)

1

<uses-feature android:name="android.hardware.nfc" android:required="true" />

<uses-feature android:name="android.hardware.nfc" android:required="true" />

2 The filtering methods of nfc are as follows:

  • ACTION_NDEF_DISCOVERED,
  • ACTION_TECH_DISCOVERED,
  • Three kinds of ACTION_TAG_DISCOVERED. The role of the filter is to filter out impurities, and the rest is what we need. These three filtering methods can be configured at the same time, such as from top to bottom three layers, as long as it meets the requirements of a certain layer of filter, it will stop to the next layer after filtering.

Add the required permissions in the filter of Activity:

ACTION_NDEF_DISCOVERED

1

2

3

4

5

6

7

<activity>

...

      <intent-filter>

        <action android:name="android.nfc.action.NDEF_DISCOVERED" />

      </intent-filter>

...

</activity>

Create a new nfc_tech_filter.xml file under <project-root>/res/xml (create xml folder yourself), and add the tag types you need to support. (The following configuration items can be multiple choices). The following example is to support NFC tag matching with NfcA and Ndef technologies.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

  <tech-list>

    <resources >

  <tech-list>

    <!--<tech>android.nfc.tech.IsoDep</tech>-->

    <tech>android.nfc.tech.NfcA</tech>

    <!--<tech>android.nfc.tech.NfcB</tech>-->

    <!--<tech>android.nfc.tech.NfcF</tech>-->

    <!--<tech>android.nfc.tech.NfcV</tech>-->

    <tech>android.nfc.tech.Ndef</tech>

    <!--<tech>android.nfc.tech.NdefFormatable</tech>-->

    <!--<tech>android.nfc.tech.MifareClassic</tech>-->

    <!--<tech>android.nfc.tech.MifareUltralight</tech>-->

  </tech-list>

</resources>

  </tech-list>

</resources>

<activity>

...

      <intent-filter>

        <action android:name="android.nfc.action.TECH_DISCOVERED" />

      </intent-filter>

 

      <meta-data

        android:name="android.nfc.action.TECH_DISCOVERED"

        android:resource="@xml/nfc_tech_filter" />

 

<meta-data android:name="android.nfc.action.TECH_DISCOVERED"

  android:resource="@xml/nfc_tech_filter" />

...

</activity>

ACTION_TAG_DISCOVERED,可以添加如下权限

 

<activity>

···

      <intent-filter>

        <action android:name="android.nfc.action.TAG_DISCOVERED" />

      </intent-filter>

···

</activity>

3 Identify the order of tags

Two nfc read operation (we read NEDF data, other bus card types can be studied by ourselves)

1 Initialize the nfc tool to determine whether there is nfc and whether nfc is open

2 After sensing the nfc tag, read and analyze the tag data corresponding to the nfc type

3 Return display

package com.example.chenqiuyang.nfcread;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chenqiuyang.nfcread.read.ParsedNdefRecord;
import com.example.chenqiuyang.nfcread.read.TextRecord;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;

/**
 * TODO:功能说明
 *
 * @author: chenqiuyang
 * @date: 2018-07-12 11:18
 */
public class NfcActivity extends Activity {

    private static final String TAG = "NfcActivity";
    private TextView tvNFCMessage;
    private PendingIntent mPendingIntent;
    private NfcAdapter mNfcAdapter;
    private Button btnClean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        Log.i(TAG, "onCreate: ");
        btnClean = findViewById(R.id.btn_clean);
        tvNFCMessage = findViewById(R.id.tv_show_nfc);




        //初始化nfc
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if (mNfcAdapter == null) {
            Toast.makeText(NfcActivity.this, "nfc is not available", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


        btnClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvNFCMessage.setText("");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        if (mNfcAdapter != null) { //有nfc功能
            if (mNfcAdapter.isEnabled()) {
                //nfc功能打开了
                //隐式启动
                mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            } else {
                Toast.makeText(NfcActivity.this, "请打开nfc功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(TAG, "onNewIntent: ");
        setIntent(intent);
        if (mNfcAdapter != null) { //有nfc功能
            if (mNfcAdapter.isEnabled()) {//nfc功能打开了
                resolveIntent(getIntent());
            } else {
                Toast.makeText(NfcActivity.this, "请打开nfc功能", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    //初次判断是什么类型的NFC卡
    private void resolveIntent(Intent intent) {
        NdefMessage[] msgs = NfcUtil.getNdefMsg(intent); //重点功能,解析nfc标签中的数据

        if (msgs == null) {
            Toast.makeText(NfcActivity.this, "非NFC启动", Toast.LENGTH_SHORT).show();
        } else {
            setNFCMsgView(msgs);
        }

    }

    /**
     * 显示扫描后的信息
     *
     * @param ndefMessages ndef数据
     */
    @SuppressLint("SetTextI18n")
    private void setNFCMsgView(NdefMessage[] ndefMessages) {
        if (ndefMessages == null || ndefMessages.length == 0) {
            return;
        }

//        tvNFCMessage.setText("Payload:" + new String(ndefMessages[0].getRecords()[0].getPayload()) + "\n");

        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        tvNFCMessage.append(hour + ":" + minute + "\n");
        List<ParsedNdefRecord> records = NdefMessageParser.parse(ndefMessages[0]);
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            ParsedNdefRecord record = records.get(i);
            tvNFCMessage.append(record.getViewText() + "\n");
        }
    }

}

 

Guess you like

Origin blog.csdn.net/guodashen007/article/details/105820641