Android支持的数据格式

数据格式的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标签的外形结构

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>

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

  1. android nfc中Ndef格式的读写

    1. 在onCreate()中获取NfcAdapter对象: NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); 2.在onNewI ...

  2. 【转】Android NFC学习笔记

    一:NFC的tag分发系统 如果想让android设备感应到NFC标签,你要保证两点 1:屏幕没有锁住 2:NFC功能已经在设置中打开 当系统检测到一个NFC标签的时候,他会自动去寻找最合适的acti ...

  3. Android NFC开发概述

    NFC手机相比普通手机来说,有以下3个附加功能:  1.可以当成POS机来用,也就是“读取”模式   2.可以当成一张卡来刷,也就是NFC技术最核心的移动支付功能  3.可以像蓝牙.Wi-Fi一样做点 ...

  4. ANDROID NFC读M1卡

    <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.Cons ...

  5. Android NFC M1卡读写&芯片卡读写(CPU卡读写)(RFID读写)

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/sgn5200/article/detai ...

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

                                           Android NFC近场通信02----读写MifareClassic卡 一.MifareClassic卡 相关 一般来 ...

  7. NFC(11)MifareUltralight格式规范及读写示例

    注意 MifareUltralight 不支三种过滤方式之一,只支持第四种(用代码,activity singleTop ) 见  NFC(4)响应NFC设备时启动activity的四重过滤机制 Mi ...

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

    Android .9.png设计 宿舍大神在做android项目,有幸得知.9.png的图形格式. 不知道大家是否注意过聊天气泡和锁屏时随着你文字的增多和你的滑动而跟着变化并且分辨率没有变低的图形?是 ...

  9. 在Android源码树中添加userspace I2C读写工具(i2c-util)

    在Android源码树中添加userspace I2C读写工具(i2c-util) http://blog.csdn.net/21cnbao/article/details/7919055 分类: A ...

随机推荐

  1. HDU 2243 考研路茫茫——单词情结(AC自动机+DP+快速幂)

    题目链接 错的上头了... 这题是DNA的加强版,26^1 +26^2... - A^1-A^2... 先去学了矩阵的等比数列求和,学的是第二种方法,扩大矩阵的方法.剩下就是各种模板,各种套. #in ...

  2. Spring MVC如何配置OpenSessionInViewInterceptor并结合Hibernate使用

    最近在使用Spring MVC开发,在使用Hibernate查询数据库的时候因为Session在DAO层被关闭导致延迟加载的属性在使用时报错,经过查询网上资料将解决方法整理如下: 我使用的是OpenS ...

  3. Redis安装部署

    Redis是一种高级key-value数据库.它跟memcached类似,不过数据 可以持久化,而且支持的数据类型很丰富.有字符串,链表,集 合和有序集合.支持在服务器端计算集合的并,交和补集(dif ...

  4. jqgrid cellEdit为true的时候,默认选中单元格值的解决方案

    jqgrid cellEdit为true的时候,点击单元格的时候,鼠标在单元格最前面闪. 这时候如果要修改数字内容,非常麻烦.要全选单元格内容,不然不好改. 点击单元格的时候,默认选中单元格值的解决方 ...

  5. 指针与数组的区别 —— 《C语言深度剖析》读书心得

    原书很多已经写的很清楚很精炼了,我也无谓做无意义的搬运,仅把一些基础和一些我自己以前容易搞混的地方写一下. 1. 意义: 指针: 指针也是一种类型,长度为4字节,其存放的内容只能是一个地址(4字节). ...

  6. [Android]用图库打开指定的文件夹,没错是第一个画面直接是图库的文件夹画面

    参考了这个里面的代码 http://bbs.csdn.net/topics/380084274 一直报错 06-16 23:58:50.698 26148-26161/com.example.myap ...

  7. *cf.4 贪心

    D. Kostya the Sculptor time limit per test 3 seconds memory limit per test 256 megabytes input stand ...

  8. jquer基础篇二

    jquery中的过滤选择器: 1.通过标签的内容来进行过滤 :contains(’内容关键字‘) 例: $("input").click(function () { $(" ...

  9. Linux下搭建Windows KMS服务器

    这几天微软发布了Windows 10 RedStone 1 Build 14390, 于是我第一时间下载进行了试用.和之前那种不激活也没有任何异样不同,现在的版本如果不激活有些功能就受限了,比如你无法 ...

  10. 别再为了iOS新系统设备而重新安装一个新版Xcode了.其实我们可以添加版本支持

    众所周知,Xcode7.3的代码补全是有问题的  如导入自定义类之后,在代码中并不会补全相应的类名... 但Xcode7.2是没有这个问题的,但很多时候我们自己的设备都升级到了iOS9.3.X系统,导 ...