android nfc中MifareClassic格式的读写

Android支持的数据格式

android nfc中MifareClassic格式的读写

数据格式的Intent filter

AndroidManifest.xml文件中,要像向下列示例那样,在<activity>元素内的<meta-data>元素中指定你创建的资源文件:

  1. <activity>
  2. ...
  3. <intent-filter>
  4. <action android:name="android.nfc.action.TECH_DISCOVERED" />
  5. </intent-filter>
  6. <meta-data
  7. android:name="android.nfc.action.TECH_DISCOVERED"
  8. android:resource="@xml/nfc_tech_filter" />
  9. ...
  10. </activity>

nfc_tech_filter.xml文件(一个Tag标签只有全部匹配tech-list元素中的tech元素指定的nfc芯片时才认为被匹配):

  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  2. <tech-list>
  3. <tech>android.nfc.tech.IsoDep</tech>
  4. <tech>android.nfc.tech.NfcA</tech>
  5. <tech>android.nfc.tech.NfcB</tech>
  6. <tech>android.nfc.tech.NfcF</tech>
  7. <tech>android.nfc.tech.NfcV</tech>
  8. <tech>android.nfc.tech.Ndef</tech>
  9. <tech>android.nfc.tech.NdefFormatable</tech>
  10. <tech>android.nfc.tech.MifareClassic</tech>
  11. <tech>android.nfc.tech.MifareUltralight</tech>
  12. </tech-list>
  13. </resources>

也可创建多个资源文件(多个资源文件是OR关系,每个资源文件中的芯片是AND关系):

  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  2. <tech-list>
  3. <tech>android.nfc.tech.NfcA</tech>
  4. <tech>android.nfc.tech.Ndef</tech>
  5. <tech>android.nfc.tech.NdefFormatable</tech>
  6. </tech-list>
  7. </resources>
  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  2. <tech-list>
  3. <tech>android.nfc.tech.Ndef</tech>
  4. <tech>android.nfc.tech.NdefFormatable</tech>
  5. </tech-list>
  6. </resources>

或者在同一个资源文件中创建多个<tech-list>元素(多个<tech-list>元素之间是OR关系,<tech-list>元素中的<tech>是AND关系):

  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  2. <tech-list>
  3. <tech>android.nfc.tech.NfcA</tech>
  4. </tech-list>
  5. <tech-list>
  6. <tech>android.nfc.tech.NfcB</tech>
  7. </tech-list>
  8. <tech-list>
  9. <tech>android.nfc.tech.MifareClassic</tech>
  10. </tech-list>
  11. </resources>

查看标签支持数据格式的方法:

通过Tag.getTechlist()方法,获得标签所支持的数据格式

通过Tag.getId()方法,获得标签的唯一ID标识

NfcAdapter == null:表示设备不支持NFC硬件

NfcAdapter.isEnable()方法:判断NFC是否开启

综上所述:

一个Tag通过Tag.getTechlist()方法获取它所支持的所有标签类型,如果清单文件中所引用的<tech-list>资源文件中所有的<tech>中的芯片是Tag标签所有支持标签的子集则被匹配的,可以写多个<tech-list>,每个<tech-list>时独立的,只要有其中一个<tech-list>中的所有的<tech>中的芯片类型全部匹配Tag所支持的芯片则认为是匹配的。多个<tech-list>是OR关系,<tech-list>中的<tech>是AND关系。

MifareClassic标签的外形结构

android nfc中MifareClassic格式的读写

MifareClassic标签的数据结构

android nfc中MifareClassic格式的读写

android nfc中MifareClassic格式的读写

注意事项(假设1k空间):

第一扇区的第一块一般用于制造商占用块

0-15个扇区:一个扇区对应4个块,所以总共有64个块,序号分别为0-63,第一个扇区对应:0-3块,第二个扇区对应:4-7块...

每个扇区的最后一个块用来存放密码或控制位,其余为数据块,一个块占用16个字节,keyA占用6字节,控制位占用4字节,keyB占用6字节

MifareClassic类的常用方法

get():根据Tag对象来获得MifareClassic对象;

Connect():允许对MifareClassic标签进行IO操作;

getType():获得MifareClassic标签的具体类型:TYPE_CLASSIC,TYPE_PLUA,TYPE_PRO,TYPE_UNKNOWN;

getSectorCount():获得标签总共有的扇区数量;

getBlockCount():获得标签总共有的的块数量;

getSize():获得标签的容量:SIZE_1K,SIZE_2K,SIZE_4K,SIZE_MINI

authenticateSectorWithKeyA(int SectorIndex,byte[] Key):验证当前扇区的KeyA密码,返回值为ture或false。

常用KeyA:默认出厂密码:KEY_DEFAULT,

各种用途的供货商必须配合该技术的MAD:KEY_MIFARE_APPLICATION_DIRECTORY

被格式化成NDEF格式的密码:KEY_NFC_FORUM

getBlockCountInSector(int):获得当前扇区的所包含块的数量;

sectorToBlock(int):当前扇区的第1块的块号;

writeBlock(int,data):将数据data写入当前块;注意:data必须刚好是16Byte,末尾不能用0填充,应该用空格

readBlock(int):读取当前块的数据。

close():禁止对标签的IO操作,释放资源。

MifareClassic标签的读写流程

获得Adapter对象

获得Tag对象

获得MifareClassic对象

读取数据块的数据

Connect(),readBlock(),close()

获得Adapter对象

获得Tag对象

获得MifareClassic对象

将数据块写入标签

Connect(),writeBlock(),close()

官方文档:

Working with tag technologies and the ACTION_TECH_DISCOVERED intent

When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, the tag dispatch system tries to start an activity with the ACTION_TECH_DISCOVERED intent. The ACTION_TECH_DISCOVERED is also used when a tag with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag directly if the tag dispatch system could not parse it for you. The basic steps when working with tag technologies are as follows:

  1. Filter for an ACTION_TECH_DISCOVERED intent specifying the tag technologies that you want to handle. SeeFiltering for NFC intents for more information. In general, the tag dispatch system tries to start aACTION_TECH_DISCOVERED intent when an NDEF message cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For more information on how this is determined, see The Tag Dispatch System.
  2. When your application receives the intent, obtain the Tag object from the intent:
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  3. Obtain an instance of a TagTechnology, by calling one of the get factory methods of the classes in theandroid.nfc.tech package. You can enumerate the supported technologies of the tag by callinggetTechList() before calling a get factory method. For example, to obtain an instance of MifareUltralightfrom a Tag, do the following:
    MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));

Reading and writing to tags

Reading and writing to an NFC tag involves obtaining the tag from the intent and opening communication with the tag. You must define your own protocol stack to read and write data to the tag. Keep in mind, however, that you can still read and write NDEF data when working directly with a tag. It is up to you how you want to structure things. The following example shows how to work with a MIFARE Ultralight tag.

package com.example.android.nfc;

import android.nfc.Tag;
import android.nfc.tech.MifareUltralight;
import android.util.Log;
import java.io.IOException;
import java.nio.charset.Charset; public class MifareUltralightTagTester {     private static final String TAG = MifareUltralightTagTester.class.getSimpleName();     public void writeTag(Tag tag, String tagText) {
        MifareUltralight ultralight = MifareUltralight.get(tag);
        try {
            ultralight.connect();
            ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
        } catch (IOException e) {
            Log.e(TAG, "IOException while closing MifareUltralight...", e);
        } finally {
            try {
                ultralight.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException while closing MifareUltralight...", e);
            }
        }
    }     public String readTag(Tag tag) {
        MifareUltralight mifare = MifareUltralight.get(tag);
        try {
            mifare.connect();
            byte[] payload = mifare.readPages(4);
            return new String(payload, Charset.forName("US-ASCII"));
        } catch (IOException e) {
            Log.e(TAG, "IOException while writing MifareUltralight
            message...", e);
        } finally {
            if (mifare != null) {
               try {
                   mifare.close();
               }
               catch (IOException e) {
                   Log.e(TAG, "Error closing tag...", e);
               }
            }
        }
        return null;
    }
}

 

例子程序:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <CheckBox
  7. android:id="@+id/checkbox_write"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:text="是否向NFC标签写入数据" />
  11. <TextView
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:layout_marginBottom="5dp"
  15. android:text="请将NFC标签或贴纸靠近手机背面"
  16. android:textSize="16sp" />
  17. <ImageView
  18. android:layout_width="match_parent"
  19. android:layout_height="match_parent"
  20. android:layout_margin="10dp"
  21. android:src="@drawable/read_nfc_tag" />
  22. </LinearLayout>

MainActivity:

  1. package mobile.android.mifareultralight;
  2. import java.io.IOException;
  3. import java.nio.charset.Charset;
  4. import android.app.Activity;
  5. import android.app.PendingIntent;
  6. import android.content.Intent;
  7. import android.nfc.NfcAdapter;
  8. import android.nfc.Tag;
  9. import android.nfc.tech.MifareClassic;
  10. import android.os.Bundle;
  11. import android.util.Log;
  12. import android.widget.CheckBox;
  13. import android.widget.Toast;
  14. public class MifareultralightMainActivity extends Activity {
  15. private CheckBox      mWriteData;
  16. private NfcAdapter    mNfcAdapter;
  17. private PendingIntent mPendingIntent;
  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_mifareultralight);
  22. mWriteData = (CheckBox) findViewById(R.id.checkbox_write);
  23. mNfcAdapter = mNfcAdapter.getDefaultAdapter(this);
  24. if (mNfcAdapter == null) {
  25. Toast.makeText(this, "设备不支持NFC!", Toast.LENGTH_LONG).show();
  26. finish();
  27. return;
  28. }
  29. if (!mNfcAdapter.isEnabled()) {
  30. Toast.makeText(this, "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
  31. finish();
  32. return;
  33. }
  34. mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
  35. getClass()), 0);
  36. }
  37. @Override
  38. public void onResume() {
  39. super.onResume();
  40. if (mNfcAdapter != null)
  41. mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
  42. null);
  43. }
  44. @Override
  45. public void onNewIntent(Intent intent) {
  46. Tag tag = intent.getParcelableExtra(mNfcAdapter.EXTRA_TAG);
  47. String[] techList = tag.getTechList();
  48. boolean haveMifareUltralight = false;
  49. for (String tech : techList) {
  50. if (tech.indexOf("MifareClassic") >= 0) {
  51. haveMifareUltralight = true;
  52. break;
  53. }
  54. }
  55. if (!haveMifareUltralight) {
  56. Toast.makeText(this, "不支持MifareClassic", Toast.LENGTH_LONG).show();
  57. return;
  58. }
  59. if (mWriteData.isChecked()) {
  60. writeTag(tag);
  61. } else {
  62. String data = readTag(tag);
  63. if (data != null) {
  64. Log.i(data, "ouput");
  65. Toast.makeText(this, data, Toast.LENGTH_LONG).show();
  66. }
  67. }
  68. }
  69. @Override
  70. public void onPause() {
  71. super.onPause();
  72. if (mNfcAdapter != null)
  73. mNfcAdapter.disableForegroundDispatch(this);
  74. }
  75. public void writeTag(Tag tag) {
  76. MifareClassic mfc = MifareClassic.get(tag);
  77. try {
  78. mfc.connect();
  79. boolean auth = false;
  80. short sectorAddress = 1;
  81. auth = mfc.authenticateSectorWithKeyA(sectorAddress,
  82. MifareClassic.KEY_NFC_FORUM);
  83. if (auth) {
  84. // the last block of the sector is used for KeyA and KeyB cannot be overwritted
  85. mfc.writeBlock(4, "1313838438000000".getBytes());
  86. mfc.writeBlock(5, "1322676888000000".getBytes());
  87. mfc.close();
  88. Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
  89. }
  90. } catch (IOException e) {
  91. // TODO Auto-generated catch block
  92. e.printStackTrace();
  93. } finally {
  94. try {
  95. mfc.close();
  96. } catch (IOException e) {
  97. // TODO Auto-generated catch block
  98. e.printStackTrace();
  99. }
  100. }
  101. }
  102. //字符序列转换为16进制字符串
  103. private String bytesToHexString(byte[] src) {
  104. StringBuilder stringBuilder = new StringBuilder("0x");
  105. if (src == null || src.length <= 0) {
  106. return null;
  107. }
  108. char[] buffer = new char[2];
  109. for (int i = 0; i < src.length; i++) {
  110. buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
  111. buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
  112. System.out.println(buffer);
  113. stringBuilder.append(buffer);
  114. }
  115. return stringBuilder.toString();
  116. }
  117. public String readTag(Tag tag) {
  118. MifareClassic mfc = MifareClassic.get(tag);
  119. for (String tech : tag.getTechList()) {
  120. System.out.println(tech);
  121. }
  122. boolean auth = false;
  123. //读取TAG
  124. try {
  125. String metaInfo = "";
  126. //Enable I/O operations to the tag from this TagTechnology object.
  127. mfc.connect();
  128. int type = mfc.getType();//获取TAG的类型
  129. int sectorCount = mfc.getSectorCount();//获取TAG中包含的扇区数
  130. String typeS = "";
  131. switch (type) {
  132. case MifareClassic.TYPE_CLASSIC:
  133. typeS = "TYPE_CLASSIC";
  134. break;
  135. case MifareClassic.TYPE_PLUS:
  136. typeS = "TYPE_PLUS";
  137. break;
  138. case MifareClassic.TYPE_PRO:
  139. typeS = "TYPE_PRO";
  140. break;
  141. case MifareClassic.TYPE_UNKNOWN:
  142. typeS = "TYPE_UNKNOWN";
  143. break;
  144. }
  145. metaInfo += "卡片类型:" + typeS + "\n共" + sectorCount + "个扇区\n共"
  146. + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize()
  147. + "B\n";
  148. for (int j = 0; j < sectorCount; j++) {
  149. //Authenticate a sector with key A.
  150. auth = mfc.authenticateSectorWithKeyA(j,
  151. MifareClassic.KEY_NFC_FORUM);
  152. int bCount;
  153. int bIndex;
  154. if (auth) {
  155. metaInfo += "Sector " + j + ":验证成功\n";
  156. // 读取扇区中的块
  157. bCount = mfc.getBlockCountInSector(j);
  158. bIndex = mfc.sectorToBlock(j);
  159. for (int i = 0; i < bCount; i++) {
  160. byte[] data = mfc.readBlock(bIndex);
  161. metaInfo += "Block " + bIndex + " : "
  162. + bytesToHexString(data) + "\n";
  163. bIndex++;
  164. }
  165. } else {
  166. metaInfo += "Sector " + j + ":验证失败\n";
  167. }
  168. }
  169. return metaInfo;
  170. } catch (Exception e) {
  171. Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
  172. e.printStackTrace();
  173. } finally {
  174. if (mfc != null) {
  175. try {
  176. mfc.close();
  177. } catch (IOException e) {
  178. Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG)
  179. .show();
  180. }
  181. }
  182. }
  183. return null;
  184. }
  185. }

清单文件:

    1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    2. package="mobile.android.mifareultralight"
    3. android:versionCode="1"
    4. android:versionName="1.0" >
    5. <uses-sdk
    6. android:minSdkVersion="15"
    7. android:targetSdkVersion="15" />
    8. <uses-permission android:name="android.permission.NFC" />
    9. <application
    10. android:icon="@drawable/ic_launcher"
    11. android:label="@string/app_name"
    12. android:theme="@style/AppTheme" >
    13. <activity
    14. android:name=".MifareultralightMainActivity"
    15. android:label="Mifareultralight"
    16. android:launchMode="singleTop"
    17. android:screenOrientation="portrait" >
    18. <intent-filter>
    19. <action android:name="android.intent.action.MAIN" />
    20. <category android:name="android.intent.category.LAUNCHER" />
    21. </intent-filter>
    22. </activity>
    23. </application>
    24. </manifest>
上一篇:Keepalived 主备配置


下一篇:vue根据不同环境打包不同的请求接口