代码实现过程如下:

读写NFC标签的纯文本数据.java

  import java.nio.charset.Charset;
import java.util.Locale; import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView; /**
* 主 Activity
* 读写NFC标签的纯文本数据
* @author dr
*
*/
public class ReadWriteTextMainActivity extends Activity {
private TextView mInputText;
private String mText; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_write_text_main); mInputText = (TextView) findViewById(R.id.textview_input_text);
} protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == 1) {
mText = data.getStringExtra("text");
mInputText.setText(mText);
}
} public void onNewIntent(Intent intent) {
// read nfc text
if (mText == null) {
// 显示NFC标签内容
Intent myIntent = new Intent(this, ShowNFCTagContentActivity.class);
myIntent.putExtras(intent);
myIntent.setAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
startActivity(myIntent); } else { // write nfc text
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { createTextRecord(mText) });
writeTag(ndefMessage, tag);
}
} /**
* 将纯文本转换成NdefRecord对象。
* @param text
* @return
*/
public NdefRecord createTextRecord(String text) {
// 得到生成语言编码字节数组
byte[] langBytes = Locale.CHINA.getLanguage().getBytes(
Charset.forName("US-ASCII"));
Charset utfEncoding = Charset.forName("UTF-8");
byte[] textBytes = text.getBytes(utfEncoding);
int utfBit = 0;
// 状态字节
char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte) status;
// 数组拷贝
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
textBytes.length); NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
return ndefRecord;
} boolean writeTag(NdefMessage ndefMessage, Tag tag) {
try {
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(ndefMessage);
return true;
} catch (Exception e) {
// TODO: handle exception
}
return false;
} // 向NFC标签写入文本
public void onClick_InputText(View view) {
Intent intent = new Intent(this, InputTextActivity.class);
startActivityForResult(intent, 1);
} }

读写NFC标签的纯文本数据.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick_InputText"
android:text="输入要写入文本" /> <TextView
android:id="@+id/textview_input_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp" /> <TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="请将NFC标签靠近手机背面读取或写入文本"
android:textColor="#F00"
android:textSize="16sp" /> <ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/read_nfc_tag" /> </LinearLayout>

显示NFC标签内容.java

 import cn.eoe.read.write.text.library.TextRecord;
import android.app.Activity;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView; /**
* 显示NFC标签内容
* @author dr
*
*/
public class ShowNFCTagContentActivity extends Activity { private TextView mTagContent;
private Tag mDetectedTag; // 传递过来的NFC的一个TAG对象
private String mTagText; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_nfctag_content);
mTagContent = (TextView) findViewById(R.id.textview_tag_content); mDetectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); Ndef ndef = Ndef.get(mDetectedTag); mTagText = ndef.getType() + "\nmax size:" + ndef.getMaxSize()
+ "bytes\n\n"; readNFCTag(); mTagContent.setText(mTagText);
} /**
*
*/
private void readNFCTag() {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msgs[] = null;
int contentSize = 0;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
contentSize += msgs[i].toByteArray().length;
}
}
try {
if (msgs != null) {
NdefRecord record = msgs[0].getRecords()[0];
TextRecord textRecord = TextRecord.parse(record);
mTagText += textRecord.getText() + "\n\ntext\n"
+ contentSize + " bytes";
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}

显示NFC标签内容.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:id="@+id/textview_tag_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp" android:layout_margin="6dp" /> </LinearLayout>

向NFC标签写入文本.java

 import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText; /**
* 向NFC标签写入文本
*
* @author dr
*
*/
public class InputTextActivity extends Activity { private EditText mTextTag; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_text);
mTextTag = (EditText) findViewById(R.id.edittext_text_tag);
} public void onClick_OK(View view) {
Intent intent = new Intent();
intent.putExtra("text", mTextTag.getText().toString());
setResult(1, intent);
finish(); }
}

向NFC标签写入文本.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="请输入要写入的文本" android:textSize="16sp" /> <EditText
android:layout_marginTop="10dp"
android:id="@+id/edittext_text_tag"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick_OK"
android:text="确定" /> </LinearLayout>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.eoe.read.write.text"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.NFC" /> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ReadWriteTextMainActivity"
android:label="读写NFC标签的纯文本数据"
android:launchMode="singleTask" >
<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.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".ShowNFCTagContentActivity"
android:label="显示NFC标签内容"
android:launchMode="singleTask" /> <activity
android:name=".InputTextActivity"
android:label="向NFC标签写入文本" /> </application> </manifest>

 DEMO:下载地址:http://download.csdn.net/detail/androidsj/7678947

10、NFC技术:读写NFC标签中的文本数据的更多相关文章

  1. JS修改标签中的文本且不影响其中标签

    /********************************************************************* * JS修改标签中的文本且不影响其中标签 * 说明: * ...

  2. 如何给HTML标签中的文本设置修饰线

    text-decoration属性介绍 text-decoration属性是用来设置文本修饰线呢,text-decoration属性一共有4个值. text-decoration属性值说明表 值 作用 ...

  3. selenium获取标签中的文本

    # 寻找文本所在的标签waitClickCompanyName = driver.find_elements_by_xpath('//div[@id="nsrzt"]//li') ...

  4. 12、NFC技术:读写NFC标签中的Uri数据

    功能实现,如下代码所示: 读写NFC标签的Uri 主Activity import cn.read.write.uri.library.UriRecord; import android.app.Ac ...

  5. android官方技术文档翻译——Case 标签中的常量字段

    本文译自androd官方技术文档<Non-constant Fields in Case Labels>,原文地址:http://tools.android.com/tips/non-co ...

  6. p标签中的文本换行

    参考文章 word-break:break-all和word-wrap:break-word的区别 CSS自动换行.强制不换行.强制断行.超出显示省略号 属性介绍 white-space: 如何处理元 ...

  7. js向标签中添加文本或其他的简例

    1.如何用js 在div内插入内容? 不是改变内容,而是插入,就是在保留原内容的基础上,在尾部添加.举个例子. 元内容<div>你好</div> 插入后<div>你 ...

  8. QT中读取文本数据(txt)

    下面的代码实现读取txt文档中的数据,并且是一行一行的读取. void MainWindow::on_pushButton_clicked() { QFile file("abcd.txt& ...

  9. 用pandas库对csv文件中的文本数据进行分析处理

    #数据分析 import pandas import csv old_path = r'd:\2000W\200W-400W.csv' f = open(old_path,'r',encoding=' ...

随机推荐

  1. PHPCMS V9添加模板自定义全局变量

    在我们使用PHPCMS V9的制作网站模板的时候,使用全局模板变量能轻松调用,使用起来非常方便,而且可以统一修改,方便维护. 下面就来讲一下在PHPCMS V9中如何添加自定义全局变量. 修改网站sy ...

  2. SIM卡

    SIM卡是(Subscriber Identity Module 客户识别模块)的缩写 也称为用户身份识别卡.智能卡,GSM数字移动电话机必须装上此卡方能使用.在电脑芯片上存储了数字移动电话客户的信息 ...

  3. [iOS]iPhone推送原理

    推送原理,先上图 说一下原理吧, 由App向iOS设备发送一个注册通知 iOS向APNs远程推送服务器发送App的Bundle Id和设备的UDID APNs根据设备的UDID和App的Bundle ...

  4. iOS:核心动画之基本动画CABasicAnimation

    基本动画,是CAPropertyAnimation的子类 属性说明: fromValue:keyPath相应属性的初始值 toValue:keyPath相应属性的结束值 动画过程说明: 随着动画的进行 ...

  5. Windows下搭建Android开发环境

    1.下载eclipse google eclipse,到官网去下载最新版的,推荐java ee版本的,当然你要用android版本或者standard也无妨 2.下载android sdk,安装相关的 ...

  6. PHP 对象和数组互相转换

    最简单的:$array = (array)$object; 但是, 如果对象的属性也是个对象的话, 就转换不了了, 就是说PHP的强制类型转换不能把对象属性中的对象转换成数组的下一个维度的数组, 刚刚 ...

  7. Android之TelephonyManager类的使用案例

    TelephonyManager类主要提供了一系列用于访问与手机通讯相关的状态和信息的get方法.其中包括手机SIM的状态和信息.电信网络的状态及手机用户的信息.在应用程序中可以使用这些get方法获取 ...

  8. Eclipse 修改debug当前行的颜色

    window --preferences--general--editors--text editors--annotations--debug current instruction pointer

  9. Toast.makeText().show() 正常使用但不显示的解决办法

    症状: toast正常构造,调用show时,不显示. View tabMeItem = tabHost.findViewById(R.id.tab_me_xc); tabMeItem.setOnCli ...

  10. hibernate学习笔记4---HQL、通用方法的抽取实现

    一.通用方法的抽取实现 由于hibernate中对增删改查的一切操作都是面向对象的,所以将增删改查抽取成通用方法,以满足不同的表的增删改查操作,简化jdbc代码. 具体例子如下: package cn ...