package com.example.mynfcdemon;

import android.app.Activity;
import android.nfc.NfcAdapter;
import android.os.Bundle;

public class MainActivity extends Activity {

//private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//nfcAdapter = NfcAdapter.getDefaultAdapter(this);
//运行APK 把标签靠近识别区即可。
}

}

-------------------------------

package com.example.mynfcdemon;

import java.io.IOException;

import android.nfc.tech.NfcV;

public class NfcVUtil {
private NfcV mNfcV;
//UID数组行式
private byte[] ID;
private String UID;
private String DSFID;
private String AFI;
//block的个数
private int blockNumber;
//一个block长度
private int oneBlockSize;
//信息
private byte[] infoRmation;

/*@function :初始化
@param :mNfcV NfcV对象
@return :返回内容byte[]
@author: :Demon 503536038@qq.com
*/

public NfcVUtil(NfcV mNfcV) throws IOException{
this.mNfcV = mNfcV;
ID = this.mNfcV.getTag().getId();
byte[] uid = new byte[ID.length];
int j = 0;
for(int i = ID.length - 1; i>=0; i-- ){
uid[j] = ID[i];
j++;
}
this.UID = printHexString(uid);

getInfoRmation();

System.out.println("UID:" + getUID()
+"AFI:" + getAFI()
+"DSFID:" + getDSFID()
+"BlockNumber:" + getBlockNumber()
+"BlockSize:" + getOneBlockSize());
}

public String getUID() {
return UID;
}

/*@function :取得标签信息
@return :返回内容byte[]
@author: :Demon 503536038@qq.com
*/
private byte[] getInfoRmation() throws IOException{
byte[] cmd = new byte[10];
cmd[0] = (byte) 0x22; //flag
cmd[1] = (byte) 0x2B; //command
System.arraycopy(ID, 0, cmd, 2, ID.length); // UID
infoRmation = mNfcV.transceive(cmd);
blockNumber = infoRmation[12];
oneBlockSize = infoRmation[13];
AFI = printHexString(new byte[]{infoRmation[11]});
DSFID = printHexString(new byte[]{infoRmation[10]});
return infoRmation;
}

public String getDSFID() {
return DSFID;
}

public String getAFI() {
return AFI;
}
public int getBlockNumber(){
return blockNumber + 1;
}

public int getOneBlockSize() {
return oneBlockSize + 1;
}

/*@function :读取一个位置在position的block
@param :position 要读取的block位置
@return :返回内容字符串
@author: :Demon 503536038@qq.com
*/
public String readOneBlock(int position) throws IOException{
byte cmd[] = new byte[11];
cmd[0] = (byte) 0x22;
cmd[1] = (byte) 0x20;
System.arraycopy(ID, 0, cmd, 2, ID.length); //UID
cmd[10] = (byte) position;
byte res[] = mNfcV.transceive(cmd);

for(int i=0; i < res.length; i++){

System.out.println("/" + res[i]);
}
String r = new String(res);
System.out.println("/" + r);

if(res[0] == 0x00){
byte block[] = new byte[res.length - 1];
System.arraycopy(res, 1, block, 0, res.length - 1);

//return printHexString(block);

String blockstr = new String(block);
return blockstr;
}
return null;
}

/*@function :读取从begin开始end个block
@instructions :begin + count 不能超过blockNumber
@param :begin block开始位置
@param :count 读取block数量
@return :返回内容字符串
@author: :Demon 503536038@qq.com
*/
public String readBlocks(int begin, int count) throws IOException{
if((begin + count)>blockNumber){
count = blockNumber - begin;
}
StringBuffer data = new StringBuffer();

for(int i = begin; i<=count + begin; i++){
data.append(readOneBlock(i));
}
return data.toString();

}

/* 将byte[]转换成16进制字符串
@param data 要转换成字符串的字节数组
@return 16进制字符串
*/
private String printHexString(byte[] data) {
StringBuffer s = new StringBuffer();;
for (int i = 0; i < data.length; i++) {
String hex = Integer.toHexString(data[i] & 0xFF);

if (hex.length() == 1) {
hex = '0' + hex;
}
s.append(hex);
}
return s.toString();
}

/* 将数据写入到block,
@param position 要写内容的block位置
@param data 要写的内容,必须长度为blockOneSize
@return false为写入失败,true为写入成功
@throws IOException */
public boolean writeBlock(int position, byte[] data) throws IOException{
byte cmd[] = new byte[15];
cmd[0] = (byte) 0x22;
cmd[1] = (byte) 0x21;
System.arraycopy(ID, 0, cmd, 2, ID.length);// UID
//block
cmd[10] = (byte) position;
//value
System.arraycopy(data, 0, cmd, 11, data.length);
byte[]rsp = mNfcV.transceive(cmd);
if(rsp[0] == 0x00){
return true;
}

return false;
}

public boolean writeStrToTag(String str){

return false;

}

}

---------------------------------

package com.example.mynfcdemon;

import java.io.IOException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;

public class TagView extends Activity{

// NFC parts
private static NfcAdapter mAdapter;
private static PendingIntent mPendingIntent;
private static IntentFilter[] mFilters;
private static String[][] mTechLists;

private TextView texttagid;
private TextView texttagdata;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tag_vierwr);
texttagdata = (TextView) findViewById(R.id.tagdatatext);
texttagid = (TextView) findViewById(R.id.tagidtext);

mAdapter = NfcAdapter.getDefaultAdapter(this);
// Create a generic PendingIntent that will be deliver to this activity.
// The NFC stack
// will fill in the intent with the details of the discovered tag before
// delivering to
// this activity.
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Setup an intent filter for all MIME based dispatches
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] { ndef, };

// Setup a tech list for all NfcV tags
mTechLists = new String[][] { new String[] { NfcV.class.getName() } };

try {
rfid_scanresult(getIntent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

void rfid_scanresult(Intent intent) throws IOException{

String action = intent.getAction();
if(NfcAdapter.ACTION_NDEF_DISCOVERED == action
|| NfcAdapter.ACTION_TECH_DISCOVERED == action
|| NfcAdapter.ACTION_TAG_DISCOVERED == action){
//if(NfcAdapter.ACTION_TECH_DISCOVERED == action){
//byte[] tagid = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] tagid = tag.getId();
//String strid = new String(tagid);
//System.out.println("TAGID:"+strid);
//System.out.println("TAGID:"+bytesToHexString(tagid));
//texttagid.setText("TagID=" + bytesToHexString(tagid));

Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NfcV nfcv = NfcV.get(tagFromIntent);
nfcv.connect();
NfcVUtil mNfcVutil = new NfcVUtil(nfcv);

texttagid.setText("UID:" + mNfcVutil.getUID()+'\n'
+"AFI:" + mNfcVutil.getAFI()+'\n'
+"DSFID:" + mNfcVutil.getDSFID()+'\n'
+"BlockNumber:" + mNfcVutil.getBlockNumber()+'\n'
+"BlockSize:" + mNfcVutil.getOneBlockSize());
//NfcVClassCard mifareClassCard=null;
texttagdata.setText("block0:"+mNfcVutil.readOneBlock(0)
+"block1:"+mNfcVutil.readOneBlock(1)+'\n'
+"block2:"+mNfcVutil.readOneBlock(2)
+"block3:"+mNfcVutil.readOneBlock(3)+'\n'
+"block4:"+mNfcVutil.readOneBlock(4)
+"block5:"+mNfcVutil.readOneBlock(5)+'\n'
+"block6:"+mNfcVutil.readOneBlock(6)
+"block7:"+mNfcVutil.readOneBlock(7)+'\n'
+"block8:"+mNfcVutil.readOneBlock(8)
+"block9:"+mNfcVutil.readOneBlock(9)+'\n'
+"block10:"+mNfcVutil.readOneBlock(10)
+"block11:"+mNfcVutil.readOneBlock(11)+'\n'
+"block12:"+mNfcVutil.readOneBlock(12)
+"block13:"+mNfcVutil.readOneBlock(13)+'\n'
+"block14:"+mNfcVutil.readOneBlock(14)
+"block15:"+mNfcVutil.readOneBlock(15)+'\n'
+"block16:"+mNfcVutil.readOneBlock(16)
+"block17:"+mNfcVutil.readOneBlock(17)+'\n'
+"block18:"+mNfcVutil.readOneBlock(18)
+"block19:"+mNfcVutil.readOneBlock(19)+'\n'
+"block20:"+mNfcVutil.readOneBlock(20)
+"block21:"+mNfcVutil.readOneBlock(21)+'\n'
+"block22:"+mNfcVutil.readOneBlock(22)
+"block23:"+mNfcVutil.readOneBlock(23)+'\n'
+"block24:"+mNfcVutil.readOneBlock(24)
+"block25:"+mNfcVutil.readOneBlock(25)+'\n'
+"block26:"+mNfcVutil.readOneBlock(26)
+"block27:"+mNfcVutil.readOneBlock(27)+'\n'
+"Read:"+ mNfcVutil.readBlocks(0, 28)
);
/*String str;
str = getNdefMessages(intent).toString();

System.out.println("Ndef::"+str);*/
String s = "kaic";
mNfcVutil.writeBlock(0, s.getBytes());

}

}

NdefMessage[] getNdefMessages(Intent intent) {
// Parse the intent
NdefMessage[] msgs = null;
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs =intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
else {
// Unknown tag type
byte[] empty = new byte[] {};
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty,empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
}
else {
// Log.e(TAG, "Unknown intent " + intent);
finish();
}
return msgs;
}

void write_NdefFormatableTag(){
/*NdefFormatable tag = NdefFormatable.get(t);
Locale locale = Locale.US;
final byte[] langBytes = locale.getLanguage().getBytes(Charsets.US_ASCII);
String text = "Tag, you're it!";
final byte[] textBytes = text.getBytes(Charsets.UTF_8);
final int utfBit = 0;
final char status = (char) (utfBit + langBytes.length);
final byte[] data = Bytes.concat(new byte[] {(byte) status}, langBytes, textBytes);
NdefRecord record = NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, newbyte[0], data);
try {
NdefRecord[] records = {text};
NdefMessage message = new NdefMessage(records);
tag.connect();
tag.format(message);
}
catch (Exception e){
//do error handling
}*/

}

public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}

}

NFC应用实例的更多相关文章

  1. NFC读写实例

    package com.sy.nfc.test; import java.io.IOException; import android.nfc.NdefMessage; import android. ...

  2. 《Android NFC 开发实战详解 》简介+源码+样章+勘误ING

    <Android NFC 开发实战详解>简介+源码+样章+勘误ING SkySeraph Mar. 14th  2014 Email:skyseraph00@163.com 更多精彩请直接 ...

  3. [安卓] 15、用NFC解锁手机并自动打开应用

    最近接到一个项目:将手机放到一个带有NFC卡的底座上手机会自动解锁,然后打开相应的应用 本人用:杭州公交通用卡做为NFC卡+Coolpad手机进行试验 效果如下: 1.手机本身带有图案锁,输对图案才能 ...

  4. Android NFC开发概述

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

  5. nfc开发

    很多Android设备已经支持NFC(近距离无线通讯技术)了.本文就以实例的方式,为大家介绍如何在Android系统中进行NFC开发. Android NFC开发环境 使用硬件:Google Nexu ...

  6. Android开发之深入理解NFC(一)

    深入理解NFC NFC(Near field communication,近场通信)也叫做近距离无线通信技术. 从原理来说,NFC和wifi类似,二者都利用无线射频技术来实现设备之间的通信. 但是,和 ...

  7. 硅谷新闻2--禁止viewpager预加载

    ContentFragment.java class MyOnPageChangeListener implements ViewPager.OnPageChangeListener { ..... ...

  8. android 技术相关Blog

    android 技术相关 LVXIANGAN的专栏 http://blog.csdn.net/LVXIANGAN/article/category/1101038 Android NFC 开发实例 h ...

  9. [转]【eoeAndroid索引】史上最牛最全android开发知识汇总

    一.开发环境搭建 (已完成) 负责人:kris 状态:已完成 所整理标签为:搭建 SDK JDK NDK Eclipse ADT 模拟器 AVD 调试器(DEBUG) DDMS 测试 日志 Logca ...

随机推荐

  1. 解决 Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. 的问题

    在web 网站开发中,经常需要连接数据库,有时候会出现这样的数据连接异常消息: 主要原因是 应用程序与数据库的连接超出了数据库连接的默认时长,在这种情况下,我们可以把数据库连接的时长延长一些,因为 C ...

  2. _config.json

    { "AUTH": "66D86F40DF42A6103C2B0C2F16E41472DABF0594C79859E5EF51E06B377215F3B464E3F0F3 ...

  3. JS常用的设计模式(11)—— 中介者模式

    中介者对象可以让各个对象之间不需要显示的相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互. 打个比方,军火买卖双方为了安全起见,找了一个信任的中介来进行交易.买家A把钱交给中介B,然后从中 ...

  4. jsp页面el表达式不起作用

    web.xml中2.4版本的默认导入的standerd.jar,和jstl.jar是使用el表达式的包是启动的而2.5版本的web.xml中默认是关闭的所以在2.5的所有jsp中需要启动一下用< ...

  5. Unieap3.5-JS常用方法

    引用js文件 获得当前主体 getDimensionId(); 当前单位类型(网点,分部,总部) getUnitType(); 数据库日期 newOracleDate(); unieap.byId(& ...

  6. url中文参数解决方案

    首先,弄清楚为什么url传递中文会转码或者乱码,以及http头 contentType="text/html; charset=GBK" 的作用. html代码会经过web服务器, ...

  7. [原]sdut2605 A^X mod P 山东省第四届ACM省赛(打表,快速幂模思想,哈希)

    本文出自:http://blog.csdn.net/svitter 题意: f(x) = K, x = 1 f(x) = (a*f(x-1) + b)%m , x > 1 求出( A^(f(1) ...

  8. C++ sstream 中处理字符串

    C++引入ostringstream.istringstream.stringstream这三个类,要使用他们创建对象就必须包含<sstream>这个头文件. istringstream的 ...

  9. luigi学习9--执行模型

    luigi的执行和触发模型非常简单. 一.luigi的执行模型 当你执行一个luigi的工作流的时候,worker调度所有的task,并且执行task在一个单独的进程中. 这种scheme最大的好处是 ...

  10. 自定义DatePicker,年月日,不显示其中某几项

    经过源码研究:该结构主要包含三个NumberPicker: private final NumberPicker mDayPicker; private final NumberPicker mMon ...