package com.sy.nfc.test;

import java.io.IOException;

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; /**
*
* @author shenyang
* @see
* @des
*
* Nfc 标签的扫描
*
*
*/
@SuppressLint("NewApi")
public class ReadTag extends Activity {
private NfcAdapter nfcAdapter;
private TextView resultText;
private PendingIntent pendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private Button mJumpTagBtn;
private boolean isFirst = true; @SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取nfc适配器,判断设备是否支持NFC功能
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, getResources().getString(R.string.no_nfc),
Toast.LENGTH_SHORT).show();
finish();
return;
} else if (!nfcAdapter.isEnabled()) {
Toast.makeText(this, getResources().getString(R.string.open_nfc),
Toast.LENGTH_SHORT).show();
finish();
return;
}
setContentView(R.layout.read_tag);
// 显示结果Text
resultText = (TextView) findViewById(R.id.resultText);
// 写入标签按钮
mJumpTagBtn = (Button) findViewById(R.id.jump);
mJumpTagBtn.setOnClickListener(new WriteBtnOnClick()); pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
ndef.addCategory("*/*");
mFilters = new IntentFilter[] { ndef };// 过滤器
mTechLists = new String[][] {
new String[] { MifareClassic.class.getName() },
new String[] { NfcA.class.getName() } };// 允许扫描的标签类型 } @SuppressLint("NewApi")
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
mTechLists);
if (isFirst) {
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
String result = processIntent(getIntent());
resultText.setText(result);
}
isFirst = false;
} } @Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
String result = processIntent(intent);
resultText.setText(result);
}
} /**
* 获取tab标签中的内容
*
* @param intent
* @return
*/
@SuppressLint("NewApi")
private String processIntent(Intent intent) {
Parcelable[] rawmsgs = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawmsgs[0];
NdefRecord[] records = msg.getRecords();
String resultStr = new String(records[0].getPayload());
return resultStr;
} /**
* 按钮点击事件
*
* @author shenyang
*
*/
class WriteBtnOnClick implements OnClickListener { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.jump:
Intent intent = new Intent(ReadTag.this, WriteTag.class);
startActivity(intent);
default:
break;
}
} } }

读标签内容代码展开

package com.sy.nfc.test;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; /**
* 写入标签
*
* @warn:弹出dialog 允许写入
* @author shenyang
*
*/
@SuppressLint("NewApi")
public class WriteTag extends Activity { private IntentFilter[] mWriteTagFilters;
private NfcAdapter nfcAdapter;
PendingIntent pendingIntent;
String[][] mTechLists;
Button writeBtn;
boolean isWrite = false;
EditText mContentEditText; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.write_tag);
writeBtn = (Button) findViewById(R.id.writeBtn);
writeBtn.setOnClickListener(new WriteOnClick());
mContentEditText = (EditText) findViewById(R.id.content_edit);
// 获取nfc适配器,判断设备是否支持NFC功能
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, getResources().getString(R.string.no_nfc),
Toast.LENGTH_SHORT).show();
finish();
return;
} else if (!nfcAdapter.isEnabled()) {
Toast.makeText(this, getResources().getString(R.string.open_nfc),
Toast.LENGTH_SHORT).show();
finish();
return;
}
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// 写入标签权限
IntentFilter writeFilter = new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED);
mWriteTagFilters = new IntentFilter[] { writeFilter };
mTechLists = new String[][] {
new String[] { MifareClassic.class.getName() },
new String[] { NfcA.class.getName() } };// 允许扫描的标签类型 } /**
* 写入标签按钮点击事件监听
*
* @author shenyang
*
*/
class WriteOnClick implements OnClickListener { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
isWrite = true;
AlertDialog.Builder builder = new AlertDialog.Builder(WriteTag.this)
.setTitle("请将标签靠近!");
builder.setNegativeButton("确定",
new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
mContentEditText.setText("");
isWrite = false;
WriteTag.this.finish();
}
});
builder.setPositiveButton("取消",
new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
isWrite = false;
}
});
builder.create();
builder.show();
}
} @Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
nfcAdapter.enableForegroundDispatch(this, pendingIntent,
mWriteTagFilters, mTechLists);
} // 写入模式时,才执行写入操作
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
if (isWrite == true
&& NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage ndefMessage = getNoteAsNdef();
if (ndefMessage != null) {
writeTag(getNoteAsNdef(), tag);
} else {
showToast("请输入您要写入标签的内容");
}
}
} // 根据文本生成一个NdefRecord
private NdefMessage getNoteAsNdef() {
String text = mContentEditText.getText().toString();
if (text.equals("")) {
return null;
} else {
byte[] textBytes = text.getBytes();
// image/jpeg text/plain
NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
"image/jpeg".getBytes(), new byte[] {}, textBytes);
return new NdefMessage(new NdefRecord[] { textRecord });
} } // 写入tag
boolean writeTag(NdefMessage message, Tag tag) { int size = message.toByteArray().length; try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect(); if (!ndef.isWritable()) {
showToast("tag不允许写入");
return false;
}
if (ndef.getMaxSize() < size) {
showToast("文件大小超出容量");
return false;
} ndef.writeNdefMessage(message);
showToast("写入数据成功.");
return true;
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
showToast("格式化tag并且写入message");
return true;
} catch (IOException e) {
showToast("格式化tag失败.");
return false;
}
} else {
showToast("Tag不支持NDEF");
return false;
}
}
} catch (Exception e) {
showToast("写入数据失败");
} return false;
} private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}

写入标签代码展开

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sy.nfc.test"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.NFC" /> <uses-feature
android:name="android.hardware.nfc"
android:required="true" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.sy.nfc.test.ReadTag"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter> <meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
</activity>
<activity android:name="com.sy.nfc.test.WriteTag" >
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>
</activity>
</application> </manifest>

配置文件展开

已经非常详细了。源码下载:

http://download.csdn.net/detail/sy_hx/6307597

可以直接运行。主要就是NFC的读写实例。有需要的下载看看

点我下载

NFC读写实例的更多相关文章

  1. NFC读写器调试总结20191203

    以下为NFC读写器调试经验总结: 1.读写器部分,从TX1/TX2输出的13.56MHZ信号主要由L0/C0构成低通滤波器,用于滤除13.56MHZ的高次谐波,取值L0=1UH,C0=47PF时候,谐 ...

  2. C# XML读写实例

    一.使用System.Xml 实例:完成如下格式配置文件的读写操作: <?xml version="1.0" encoding="UTF-8"?> ...

  3. NFC读写电子便签总结

    编写NFC程序的基本步骤 1)设置权限,限制Android版本.安装的设备: 1 2 3 4 <uses-sdk android:minSdkVersion="14"/> ...

  4. NFC应用实例

    package com.example.mynfcdemon; import android.app.Activity;import android.nfc.NfcAdapter;import and ...

  5. boost::lockfree::queue多线程读写实例

    最近的任务是写一个多线程的东西,就得接触多线程队列了,我反正是没学过分布式的,代码全凭感觉写出来的,不过运气好,代码能够work= = 话不多说,直接给代码吧,一个多消费者,多生产者的模式.假设我的任 ...

  6. 13.56Mhz/NFC读写器天线阻抗匹配调试步骤-20191128

    相关原文: https://blog.csdn.net/wwt18811707971/article/details/80641432 http://www.52rd.com/Blog/Detail_ ...

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

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

  8. NFC应用(二)读写器模式

    NFC第二种应用场境就是所谓的读写器模式.既然有卡,当然就会有读写器,这两种模式是配合在一起使用的.两个卡放一起不能通信,两个读写器模式的设备也不能通信. NFC读写器一般支持以下一种或多种协议:Mi ...

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

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

随机推荐

  1. jstack工具查看系统线程问题

    背景: 最近在做项目系统的异常测试,项目依赖于nkv,需要模拟依赖组件nkv异常时系统的响应及性能情况.通过tc工具模拟当服务器发送到nkv的请求超时时系统的响应.发现接口返回错误率100%,查看服务 ...

  2. thinkphp模型

    1.获取系统常量信息的方法:在控制器DengLuController里面下写入下面的方法,然后调用该方法. public function test() { //echo "这是测试的&qu ...

  3. Excel—使用条件格式标注今日值班者

    如下图所示值班表: Step1:选中A2:G2,调出条件格式,在条件格式中,使用公式确定单元格. Step2: 在公式栏中填入以下公式: =TEXT(TODAY(),"aaaa") ...

  4. 【WP8.1】HttpClient网络请求、进度以及终止

    工作这么长时间,起初还是喜欢用面向程序过程的思路去写代码. 慢慢的才会用面向对象的思路分析.解决问题.也算是一点点进步吧. 最近在做一个下载音乐的功能.用到了HttpClient类. 于是就简单的写了 ...

  5. js中bind,call,apply方法的应用

    最近用js的类写东西,发现一个无比蛋疼的事,那就是封装的类方法中的this指针经常会改变指向,失去上下文,导致程序错误或崩溃. 比如: function Obj(){ this.type = &quo ...

  6. UML类图符号 各种关系说明以及举例

    UML中描述对象和类之间相互关系的方式包括:依赖,关联,聚合,组合,泛化,实现等. 表示关系的强弱:组合>聚合>关联>依赖 相互间关系 聚合是表明对象之间的整体与部分关系的关联,而组 ...

  7. codeblocks16.01 中配置Opencv3 姿势

    VS太大安装时间长,考虑到效率问题,可以使用opencv+codeblocks opencv3没有codeblocks版本,需要自己编译,编译过程略. 已编译版本下载地址 http://pan.bai ...

  8. angular路由详解:

    1.$routeProvider ngRoute模块中的服务 2.otherwise:设置用于路由改变时,与任何其他定义的路由无法匹配的时候执行的代码 3.when:为$route服务定义新的路由 例 ...

  9. HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application 错误

    解决方法链接:http://stackoverflow.com/questions/17709076/http-status-500-the-absolute-uri-http-java-sun-co ...

  10. shell语法

    基本语法列表 #linux组成:内核+工具 #linux启动: . getty:提示登录名和密码,输入之后调用login . login:login验证用户名和密码,然后调用shell . shell ...