如何读取数据?

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

NfcA nfcA = NfcA.get(tag);
   nfcA.connect();

byte[] SELECT = {(byte) 0x30, (byte) 0x05};//我读取的NFC卡片使用的是NTAG216的芯片,这里的指令参数是根据其datasheet的说明写的。

byte[] result = nfcA.transceive(SELECT);//这里会返回16个字节的数据,根据芯片不同会有差异

该芯片的快速读写命令是0x3A,可以指定读取页数范围,在使用快速读写命令时,发现读取范围超过70字节android就会报错,所以使用了每次最多读取64字节的方式。

  1. package com.yorkg.android.nfc;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7.  
  8. import android.app.Activity;
  9. import android.app.AlertDialog;
  10. import android.app.PendingIntent;
  11. import android.content.DialogInterface;
  12. import android.content.Intent;
  13. import android.content.IntentFilter;
  14. import android.nfc.NfcAdapter;
  15. import android.nfc.Tag;
  16. import android.nfc.tech.MifareClassic;
  17. import android.nfc.tech.NfcA;
  18. import android.os.Bundle;
  19. import android.view.View;
  20. import android.view.View.OnClickListener;
  21. import android.view.Window;
  22. import android.widget.Button;
  23. import android.widget.EditText;
  24. import android.widget.Toast;
  25.  
  26. import com.yorkg.android.nfc.dataobject.mifare.MifareBlock;
  27. import com.yorkg.android.nfc.dataobject.mifare.MifareClassCard;
  28. import com.yorkg.android.nfc.dataobject.mifare.MifareSector;
  29. import com.yorkg.android.nfc.util.Converter;
  30.  
  31. public class MyFirstNFCDemoActivity extends Activity {
  32. /** Called when the activity is first created. */
  33.  
  34. private Button clearBtn = null;
  35.  
  36. private EditText sealCompanyName = null;
  37. private EditText sealName = null;
  38. private EditText sealNumber = null;
  39. private EditText sealTaxId = null;
  40. private EditText sealCode = null;
  41. private EditText sealMaterial = null;
  42. private EditText sealSize = null;
  43.  
  44. private EditText companyMadedName = null;
  45. private EditText companyMadedTime = null;
  46.  
  47. private EditText companyCheckedName = null;
  48.  
  49. private NfcAdapter mAdapter;
  50. private PendingIntent mPendingIntent;
  51. private IntentFilter[] mFilters;
  52. private String[][] mTechLists;
  53.  
  54. private static final int AUTH = 1;
  55. private static final int EMPTY_BLOCK_0 = 2;
  56. private static final int EMPTY_BLOCK_1 = 3;
  57. private static final int NETWORK = 4;
  58. private static final int NFC_OFF = 5;
  59. private static final int NFC_TYPE_ERROR = 6;
  60. private static final String TAG = "NfcDemo";
  61.  
  62. private static boolean READ_LOCK = false;
  63.  
  64. private void initView(){
  65. sealCompanyName = (EditText) this.findViewById(R.id.edittext_seal_company_name);
  66. sealName = (EditText) this.findViewById(R.id.edittext_seal_name);
  67. sealNumber = (EditText) this.findViewById(R.id.edittext_seal_number);
  68. sealTaxId = (EditText) this.findViewById(R.id.edittext_tax_id);
  69. sealCode = (EditText) this.findViewById(R.id.edittext_code);
  70. sealMaterial = (EditText) this.findViewById(R.id.edittext_seal_material);
  71. sealSize = (EditText) this.findViewById(R.id.edittext_seal_size);
  72.  
  73. companyMadedName = (EditText) this.findViewById(R.id.edittext_company_maded_name);
  74. companyMadedTime = (EditText) this.findViewById(R.id.edittext_company_maded_time);
  75.  
  76. companyCheckedName = (EditText) this.findViewById(R.id.edittext_company_checked_name);
  77.  
  78. clearBtn = (Button) this.findViewById(R.id.clear_btn);
  79. clearBtn.setOnClickListener(new OnClickListener() {
  80.  
  81. @Override
  82. public void onClick(View v) {
  83. // TODO Auto-generated method stub
  84. cleanData();
  85. }
  86. });
  87. }
  88.  
  89. //清除数据信息
  90. private void cleanData(){
  91. sealCompanyName.setText("");
  92. sealName.setText("");
  93. sealNumber.setText("");
  94. sealTaxId.setText("");
  95. sealCode.setText("");
  96. sealMaterial.setText("");
  97. sealSize.setText("");
  98. companyMadedName.setText("");
  99. companyMadedTime.setText("");
  100. companyCheckedName.setText("");
  101. }
  102.  
  103. @Override
  104. public void onCreate(Bundle savedState) {
  105. super.onCreate(savedState);
  106. requestWindowFeature(Window.FEATURE_NO_TITLE);
  107. setContentView(R.layout.main);
  108.  
  109. initView();
  110.  
  111. mAdapter = NfcAdapter.getDefaultAdapter(this);
  112. mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
  113.  
  114. // Setup an intent filter for all MIME based dispatches
  115. IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
  116. // try {
  117. // ndef.addDataType("*/*");
  118. // } catch (MalformedMimeTypeException e) {
  119. // throw new RuntimeException("fail", e);
  120. // }
  121. mFilters = new IntentFilter[] { ndef, };
  122. mTechLists = new String[][] { new String[] { MifareClassic.class
  123. .getName() } , new String[] {NfcA.class.getName()}};
  124.  
  125. //得到是否检测到ACTION_TECH_DISCOVERED触发
  126. if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
  127. //处理该intent
  128. resolveIntentNfcA(getIntent());
  129. }
  130. }
  131.  
  132. @Override
  133. public void onResume() {
  134. super.onResume();
  135.  
  136. if (mAdapter!=null && (!mAdapter.isEnabled())) {
  137. showAlert(NFC_OFF, getString(R.string.error5));
  138. }
  139.  
  140. if (mAdapter!=null) {
  141. mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
  142. mTechLists);
  143. }
  144.  
  145. }
  146.  
  147. @Override
  148. public void onNewIntent(Intent intent) {
  149. resolveIntentNfcA(intent);
  150. }
  151.  
  152. @Override
  153. public void onPause() {
  154. super.onPause();
  155. if (mAdapter!=null){
  156. mAdapter.disableForegroundDispatch(this);
  157. }
  158. }
  159. void resolveIntentNfcA(Intent intent){
  160. if (READ_LOCK==false){
  161. READ_LOCK = true;
  162. Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  163.  
  164. if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))
  165. {
  166. Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  167. MyLog.i(TAG, Arrays.toString(tagFromIntent.getTechList()));
  168.  
  169. try
  170. {
  171. NfcA nfcA = NfcA.get(tag);
  172. nfcA.connect();
  173. byte[] SELECT = {
  174. (byte) 0x30,
  175. (byte) 0x05,
  176. };
  177.  
  178. byte[] result = nfcA.transceive(SELECT);
  179. int data_len = ((result[0]&0x0f)<<8)+((result[1]&0xff));
  180. MyLog.i(TAG, "是否已写入数据"+result[0]+",写入数据长度:"+data_len);
  181. byte[] buf_res = new byte[data_len/2+4];
  182. if (result[0]!=0 && data_len!=0){
  183. int count = data_len/2/64;
  184. int i = 0;
  185. for (i=0; i<count; i++){
  186. // //读取数据
  187. byte[] DATA_READ = {
  188. (byte) 0x3A,
  189. (byte) (0x06+i*(64/4)),
  190. (byte) (0x06+(i+1)*(64/4))
  191. // (byte) (5+data_len/8)
  192. };
  193. byte[] data_res = nfcA.transceive(DATA_READ);
  194. System.arraycopy(data_res, 0, buf_res, i*64, 64);
  195. MyLog.i(TAG, "读卡成功");
  196. }
  197. if (((data_len/2)%(64))!=0){
  198. byte[]DATA_READ = {
  199. (byte) 0x3A,
  200. (byte) (0x06+i*(64/4)),
  201. (byte) (((0x06+i*(64/4))+(data_len/2/4)%(64/4))-1)
  202. // (byte) (5+data_len/8)
  203. };
  204. byte[] data_res = nfcA.transceive(DATA_READ);
  205. System.arraycopy(data_res, 0, buf_res, i*64, (data_len/2)%64);
  206. MyLog.i(TAG, "读卡成功2");
  207. }
  208. String res = gb2312ToString(buf_res);
  209. MyLog.i(TAG, "stringBytes:"+res);
  210. showNFCInfo(res);
  211. }
  212.  
  213. }catch(IOException e){
  214. e.printStackTrace();
  215. cleanData();
  216. MyLog.e(TAG, "读卡失败");
  217. }catch (Exception e) {
  218. // TODO: handle exception
  219. e.printStackTrace();
  220. showAlert(NFC_TYPE_ERROR, getString(R.string.error6));
  221. }finally{
  222.  
  223. }
  224.  
  225. }
  226. READ_LOCK = false;
  227. }
  228. }
  229.  
  230. //将数据转换为GB2312
  231. private String gb2312ToString(byte[] data) {
  232. String str = null;
  233. try {
  234. str = new String(data, "gb2312");//"utf-8"
  235. } catch (UnsupportedEncodingException e) {
  236. }
  237. return str;
  238. }
  239.  
  240. //将字符串解析显示到页面
  241. private void showNFCInfo(String str){
  242. String[] contents_temp = str.split("\\|");
  243. String[] contents = new String[contents_temp.length];
  244.  
  245. int i;
  246.  
  247. for (i = 0; i < contents_temp.length; i++) {
  248. contents[i]=contents_temp[i];
  249. }
  250. //目前有10项,所以这里只初始化到第10项
  251. for (int j=i; j<10; j++){
  252. contents[j]="";
  253. }
  254.  
  255. if (contents[0]!=null){
  256. sealCompanyName.setText(contents[0]);
  257. }
  258. if (contents[1]!=null){
  259. sealName.setText(contents[1]);
  260. }
  261. if (contents[2]!=null){
  262. sealNumber.setText(contents[2]);
  263. }
  264.  
  265. if (contents[3]!=null){
  266. sealTaxId.setText(contents[3]);
  267. }
  268.  
  269. if (contents[4]!=null){
  270. sealCode.setText(contents[4]);
  271. }
  272.  
  273. if (contents[5]!=null){
  274. sealMaterial.setText(contents[5]);
  275. }
  276. if (contents[6]!=null){
  277. sealSize.setText(contents[6]);
  278. }
  279.  
  280. if (contents[7]!=null){
  281. companyMadedName.setText(contents[7]);
  282. }
  283. if (contents[8]!=null){
  284. companyMadedTime.setText(contents[8]);
  285. }
  286.  
  287. if (contents[9]!=null){
  288. companyCheckedName.setText(contents[9]);
  289. }
  290.  
  291. }
  292.  
  293. private void showAlert(int alertCase,String str) {
  294. // prepare the alert box
  295. AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
  296. switch (alertCase) {
  297.  
  298. case AUTH:// Card Authentication Error
  299. alertbox.setMessage(getString(R.string.error1));
  300. break;
  301. case EMPTY_BLOCK_0: // Block 0 Empty
  302. alertbox.setMessage(getString(R.string.error2));
  303. break;
  304. case EMPTY_BLOCK_1:// Block 1 Empty
  305. alertbox.setMessage(getString(R.string.error3));
  306. break;
  307. case NETWORK: // Communication Error
  308. alertbox.setMessage(getString(R.string.error4));
  309. break;
  310. case NFC_OFF:
  311. alertbox.setMessage(getString(R.string.error5));
  312. break;
  313. case NFC_TYPE_ERROR:
  314. alertbox.setMessage(getString(R.string.error6));
  315. }
  316. // set a positive/yes button and create a listener
  317. alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  318.  
  319. // Save the data from the UI to the database - already done
  320. public void onClick(DialogInterface arg0, int arg1) {
  321. clearFields();
  322. }
  323. });
  324. // display box
  325. alertbox.show();
  326.  
  327. }
  328.  
  329. private void clearFields() {
  330.  
  331. }
  332. }

读取NfcA格式数据的更多相关文章

  1. Android读取JSON格式数据

    Android读取JSON格式数据 1. 何为JSON? JSON,全称为JavaScript Object Notation,意为JavaScript对象表示法. JSON 是轻量级的文本数据交换格 ...

  2. R语言笔记001——读取csv格式数据

    读取csv格式数据 数据来源是西南财经大学 司亚卿 老师的课程作业 方法一:read.csv()函数 file.choose() read.csv("C:\\Users\\Administr ...

  3. ArcGIS读取dem格式数据

    DEM是GIS常用的一种数据,用来做各种分析.展示等,十分有用!它实质上就是一个栅格,只不过这个栅格值表示高程,常用的格式是tif,grid等.今天听到了另外一种说法:*.dem是最常见到的DEM的格 ...

  4. Pandas 读取文本格式数据

    title 其实书中说的我认为不够全,因为公司里面现在主要用stata和spss,暂时还没有用到sas,excel也很少用 那么读取文件的方式,因为有人已经总结了,我就偷过来算了 对应不同的文件类型有 ...

  5. Java读取lob格式数据

    想要读出lob里面的图片数据,就要确认clob里面存储的是什么,一般情况下存储的base64的串串.所以就以base64为例,而Blob里面存储的大部分是图片数据,但也有xml内容数据. 1查询lob ...

  6. C# 读取CSV格式数据 读取为DataTable类型

    先贴代码: using System.Data;using System.Data.OleDb; static void Main(string[] args) { var strpath = Sys ...

  7. R语言XML格式数据导入与处理

    数据解析 XML是一种可扩展标记语言,它被设计用来传输和存储数据.XML是各种应用程序之间进行数据传输的最常用的工具.它与Access,Oracle和SQL Server等数据库不同,数据库提供了更强 ...

  8. 基于GDAL库,读取海洋风场数据(.nc格式)c++版

    经过这一段时间的对海洋数据的处理,接触了大量的与海洋相关的数据,例如海洋地形.海洋表面温度.盐度.湿度.云场.风场等数据,除了地形数据是grd格式外,其他的都是nc格式的数据.本文将以海洋风场数据为例 ...

  9. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(十一)定制一个arvo格式文件发送到kafka的topic,通过Structured Streaming读取kafka的数据

    将arvo格式数据发送到kafka的topic 第一步:定制avro schema: { "type": "record", "name": ...

随机推荐

  1. MAC地址与IP地址的区别

    介绍一下MAC地址的知识,MAC地址和IP地址的区别以及MAC地址在实际应用中所涉及到的安全问题. 一.基础知识 如今的网络是分层来实现的,就像是搭积木一样,先设计某个特定功能的模块,然后把模块拼起来 ...

  2. 使用powershell提权的一些技巧

    原文:http://fuzzysecurity.com/tutorials/16.html 翻译:http://www.myexception.cn/windows/1752546.html http ...

  3. Learn ZYNQ Programming(1)

    GPIO LED AND KEY: part1:gpio leds and gpio btns combination. (include 1~4) part2:use gpio btns inter ...

  4. thinkphp的field方法的用法

    ThinkPHP的连贯操作方法中field方法有很多的使用技巧,field方法主要目的是标识要返回或者操作的字段. 1.用于查询 在查询操作中field方法是使用最频繁的. $Model->fi ...

  5. SVN 的安装与配置

    1.下载subclipse1.6的site包 2.把这个site-1.6.2解压开,将其内部的文件,全部放到 C:\Program Files\MyEclipse\MyEclipse 9\dropin ...

  6. ffmpeg命令行

    ubuntu下简单安装ffmpeg sudo add-apt-repository ppa:kirillshkrogalev/ffmpeg-nextsudo apt-get update sudo a ...

  7. IOS第17天(1,Quartz2D图片水印)

    ****图片 水印 #import "HMViewController.h" @interface HMViewController () @property (weak, non ...

  8. File类的createNewFile()与createTempFile()的区别

    最近,在看代码时看到了一个方法, File.createTempFile() ,由此联想到File.createNewFile() 方法,一时间不知道两者到底有什么区别,感觉都是创建新文件嘛,后来查看 ...

  9. 怎样成为全栈工程师(Full Stack Developer)?

    "Facebook 工程师说 Facebook 只招 full stack engineer,那么 Facebook engineer 都是怎样的人啦."? 具体经验不重要,重要的 ...

  10. eclipse创建web项目

    总结为3步: 必备环境: Eclipse jee Tomcat 1.创建services 2.创建dynamic web project项目 3.WebContent路径下创建index.jsp 运行 ...