android nfc中MifareClassic格式的读写

Android支持的数据格式

数据格式的Intent filter

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

[html] view plaincopyprint?

  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芯片时才认为被匹配):

[html] view plaincopyprint?

  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关系):

[html] view plaincopyprint?

  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>

[html] view plaincopyprint?

  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关系):

[html] view plaincopyprint?

  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标签的外形结构

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

 

例子程序:

[html] view plaincopyprint?

  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:

[java] view plaincopyprint?

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

清单文件:

[html] view plaincopyprint?

    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>
时间: 2024-10-10 09:13:56

android nfc中MifareClassic格式的读写的相关文章

android nfc中Ndef格式的读写

检测到标签后在Activity中的处理流程 1. 在onCreate()中获取NfcAdapter对象: NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); 2.在onNewIntent()中获取Tag对象或者NdefMessage信息: 获取Tag对象: Tag tag = intent.getParcelableExra(NfcAdapter.EXTRA_TAG); 获取NdefMessage信息: Parcelable[]

android nfc(官方翻译)

为了充分详细的学习nfc相关的知识,决定阅读官方英文文档,并翻译下来供大家阅读. NFC Basics There are two major uses cases when working with NDEF data and Android: Reading NDEF data from an NFC tag Beaming NDEF messages from one device to another with Android Beam? The Tag Dispatch System

【转】Android NFC学习笔记

一:NFC的tag分发系统 如果想让android设备感应到NFC标签,你要保证两点 1:屏幕没有锁住 2:NFC功能已经在设置中打开 当系统检测到一个NFC标签的时候,他会自动去寻找最合适的activity去处理这个intent. 他所发出的这个Intent将会有三种action: ACTION_NDEF_DISCOVERED:当系统检测到tag中含有NDEF格式的数据时,且系统中有activity声明可以接受包含NDEF数据的Intent的时候,系统会优先发出这个action的intent.

Android NFC近场通信03----读写MifareClassic卡

                                       Android NFC近场通信02----读写MifareClassic卡 一.MifareClassic卡 相关 一般来说,给予MifareClassic的射频卡,一般内存大小有3种: 1K: 16个分区(sector),每个分区4个块(block),每个块(block) 16个byte数据 2K: 32个分区,每个分区4个块(block),每个块(block) 16个byte数据 4K:64个分区,每个分区4个块(

Delphi中Json格式读写

Json是一种轻量级数据传输格式,广泛应用互联网和各应用中,json主要采用键值对来表示数据项,多个数据项之间用逗号分隔,也可以用于数组.下面注重介绍一下在delphi中使用json,在delphi中使用json常用superobject单元文件,该文件可以在网上下载,最初接触json是在2011年,好久没用这不刚好有项目要用到又折腾了好久,下面做了一个简单的Demo,方便以后忘了能随时查看,具体的json使用可以参看万一老师的博客,记录的很详细,下面的demo主要是将数据库记录转换为json格

Android中向SD卡读写数据,读SD卡和手机内存

package com.example.sdoperation; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import android.support.v7.app.Actio

Android开发中 .9.png格式图形设计:

Android .9.png设计 宿舍大神在做android项目,有幸得知.9.png的图形格式. 不知道大家是否注意过聊天气泡和锁屏时随着你文字的增多和你的滑动而跟着变化并且分辨率没有变低的图形?是否好奇过它是怎么实现的? 该图片格式应用于Android设计中需要根据文字多少或其他条件而可以伸缩的图形外框,(应用于聊天气泡和滑动锁屏等). 而设计这种格式的不是ps等图片.处理工具而是Android-sdk里自带的draw9path.bat工具.  先找到自己电脑上的D:\you yong\El

Android中SdCard的数据读写

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.R.integer; import android.content.Context; import android.os.Environment; public class FileService { private Context context; public Fil

android studio中使用x5 webview来读写cookies的问题

本人新手,刚接触AS也没有多久,记录下两个问题. 1. 怎么在android studio中写入cookies 把写入cookies的动作放在了主界面的onCreate事件中了,看了腾讯的说明,说是要放在X5初始化完成以后,在这里应该已经初始化完成了. String url="http://wx.xxxxxxx.com.cn"; com.tencent.smtt.sdk.CookieSyncManager.createInstance(this); com.tencent.smtt.s