10、NFC技术:读写NFC标签中的文本数据
代码实现过程如下:
读写NFC标签的纯文本数据.java
1 import java.nio.charset.Charset; 2 import java.util.Locale; 3 4 import android.app.Activity; 5 import android.content.Intent; 6 import android.nfc.NdefMessage; 7 import android.nfc.NdefRecord; 8 import android.nfc.NfcAdapter; 9 import android.nfc.Tag; 10 import android.nfc.tech.Ndef; 11 import android.os.Bundle; 12 import android.view.View; 13 import android.widget.TextView; 14 15 /** 16 * 主 Activity 17 * 读写NFC标签的纯文本数据 18 * @author dr 19 * 20 */ 21 public class ReadWriteTextMainActivity extends Activity { 22 private TextView mInputText; 23 private String mText; 24 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 // TODO Auto-generated method stub 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_read_write_text_main); 30 31 mInputText = (TextView) findViewById(R.id.textview_input_text); 32 } 33 34 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 35 if (requestCode == 1 && resultCode == 1) { 36 mText = data.getStringExtra("text"); 37 mInputText.setText(mText); 38 } 39 } 40 41 public void onNewIntent(Intent intent) { 42 // read nfc text 43 if (mText == null) { 44 // 显示NFC标签内容 45 Intent myIntent = new Intent(this, ShowNFCTagContentActivity.class); 46 myIntent.putExtras(intent); 47 myIntent.setAction(NfcAdapter.ACTION_NDEF_DISCOVERED); 48 startActivity(myIntent); 49 50 } else { // write nfc text 51 Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 52 NdefMessage ndefMessage = new NdefMessage( 53 new NdefRecord[] { createTextRecord(mText) }); 54 writeTag(ndefMessage, tag); 55 } 56 } 57 58 /** 59 * 将纯文本转换成NdefRecord对象。 60 * @param text 61 * @return 62 */ 63 public NdefRecord createTextRecord(String text) { 64 // 得到生成语言编码字节数组 65 byte[] langBytes = Locale.CHINA.getLanguage().getBytes( 66 Charset.forName("US-ASCII")); 67 Charset utfEncoding = Charset.forName("UTF-8"); 68 byte[] textBytes = text.getBytes(utfEncoding); 69 int utfBit = 0; 70 // 状态字节 71 char status = (char) (utfBit + langBytes.length); 72 73 byte[] data = new byte[1 + langBytes.length + textBytes.length]; 74 data[0] = (byte) status; 75 // 数组拷贝 76 System.arraycopy(langBytes, 0, data, 1, langBytes.length); 77 System.arraycopy(textBytes, 0, data, 1 + langBytes.length, 78 textBytes.length); 79 80 NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, 81 NdefRecord.RTD_TEXT, new byte[0], data); 82 return ndefRecord; 83 } 84 85 boolean writeTag(NdefMessage ndefMessage, Tag tag) { 86 try { 87 Ndef ndef = Ndef.get(tag); 88 ndef.connect(); 89 ndef.writeNdefMessage(ndefMessage); 90 return true; 91 } catch (Exception e) { 92 // TODO: handle exception 93 } 94 return false; 95 } 96 97 // 向NFC标签写入文本 98 public void onClick_InputText(View view) { 99 Intent intent = new Intent(this, InputTextActivity.class); 100 startActivityForResult(intent, 1); 101 } 102 103 }
读写NFC标签的纯文本数据.xml
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 7 <Button 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:onClick="onClick_InputText" 11 android:text="输入要写入文本" /> 12 13 <TextView 14 android:id="@+id/textview_input_text" 15 android:layout_width="match_parent" 16 android:layout_height="wrap_content" 17 android:textSize="16sp" /> 18 19 <TextView 20 21 android:layout_width="match_parent" 22 android:layout_height="wrap_content" 23 android:layout_marginTop="30dp" 24 android:text="请将NFC标签靠近手机背面读取或写入文本" 25 android:textColor="#F00" 26 android:textSize="16sp" /> 27 28 <ImageView 29 android:layout_width="match_parent" 30 android:layout_height="match_parent" 31 android:src="@drawable/read_nfc_tag" /> 32 33 </LinearLayout>
显示NFC标签内容.java
1 import cn.eoe.read.write.text.library.TextRecord; 2 import android.app.Activity; 3 import android.nfc.NdefMessage; 4 import android.nfc.NdefRecord; 5 import android.nfc.NfcAdapter; 6 import android.nfc.Tag; 7 import android.nfc.tech.Ndef; 8 import android.os.Bundle; 9 import android.os.Parcelable; 10 import android.widget.TextView; 11 12 13 /** 14 * 显示NFC标签内容 15 * @author dr 16 * 17 */ 18 public class ShowNFCTagContentActivity extends Activity { 19 20 private TextView mTagContent; 21 private Tag mDetectedTag; // 传递过来的NFC的一个TAG对象 22 private String mTagText; 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 // TODO Auto-generated method stub 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.activity_show_nfctag_content); 29 mTagContent = (TextView) findViewById(R.id.textview_tag_content); 30 31 mDetectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); 32 33 Ndef ndef = Ndef.get(mDetectedTag); 34 35 mTagText = ndef.getType() + "\nmax size:" + ndef.getMaxSize() 36 + "bytes\n\n"; 37 38 readNFCTag(); 39 40 mTagContent.setText(mTagText); 41 } 42 43 /** 44 * 45 */ 46 private void readNFCTag() { 47 if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { 48 Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra( 49 NfcAdapter.EXTRA_NDEF_MESSAGES); 50 NdefMessage msgs[] = null; 51 int contentSize = 0; 52 if (rawMsgs != null) { 53 msgs = new NdefMessage[rawMsgs.length]; 54 for (int i = 0; i < rawMsgs.length; i++) { 55 msgs[i] = (NdefMessage) rawMsgs[i]; 56 contentSize += msgs[i].toByteArray().length; 57 } 58 } 59 try { 60 if (msgs != null) { 61 NdefRecord record = msgs[0].getRecords()[0]; 62 TextRecord textRecord = TextRecord.parse(record); 63 mTagText += textRecord.getText() + "\n\ntext\n" 64 + contentSize + " bytes"; 65 } 66 } catch (Exception e) { 67 // TODO: handle exception 68 } 69 } 70 } 71 }
显示NFC标签内容.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent" 4 android:orientation="vertical" > 5 6 <TextView 7 android:id="@+id/textview_tag_content" 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:textSize="16sp" android:layout_margin="6dp" /> 11 12 </LinearLayout>
向NFC标签写入文本.java
1 import android.app.Activity; 2 import android.content.Intent; 3 import android.os.Bundle; 4 import android.view.View; 5 import android.widget.EditText; 6 7 /** 8 * 向NFC标签写入文本 9 * 10 * @author dr 11 * 12 */ 13 public class InputTextActivity extends Activity { 14 15 private EditText mTextTag; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_input_text); 21 mTextTag = (EditText) findViewById(R.id.edittext_text_tag); 22 } 23 24 public void onClick_OK(View view) { 25 Intent intent = new Intent(); 26 intent.putExtra("text", mTextTag.getText().toString()); 27 setResult(1, intent); 28 finish(); 29 30 } 31 }
向NFC标签写入文本.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <TextView 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 11 android:text="请输入要写入的文本" android:textSize="16sp" /> 12 13 <EditText 14 android:layout_marginTop="10dp" 15 android:id="@+id/edittext_text_tag" 16 android:layout_width="match_parent" 17 android:layout_height="wrap_content" /> 18 19 <Button 20 android:layout_width="match_parent" 21 android:layout_height="wrap_content" 22 android:onClick="onClick_OK" 23 android:text="确定" /> 24 25 </LinearLayout>
1 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 2 package="cn.eoe.read.write.text" 3 android:versionCode="1" 4 android:versionName="1.0" > 5 6 <uses-sdk 7 android:minSdkVersion="15" 8 android:targetSdkVersion="15" /> 9 10 <uses-permission android:name="android.permission.NFC" /> 11 12 <application 13 android:icon="@drawable/ic_launcher" 14 android:label="@string/app_name" 15 android:theme="@style/AppTheme" > 16 <activity 17 android:name=".ReadWriteTextMainActivity" 18 android:label="读写NFC标签的纯文本数据" 19 android:launchMode="singleTask" > 20 <intent-filter> 21 <action android:name="android.intent.action.MAIN" /> 22 <category android:name="android.intent.category.LAUNCHER" /> 23 </intent-filter> 24 <intent-filter> 25 <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 26 <category android:name="android.intent.category.DEFAULT" /> 27 <data android:mimeType="text/plain" /> 28 </intent-filter> 29 </activity> 30 <activity 31 android:name=".ShowNFCTagContentActivity" 32 android:label="显示NFC标签内容" 33 android:launchMode="singleTask" /> 34 35 <activity 36 android:name=".InputTextActivity" 37 android:label="向NFC标签写入文本" /> 38 39 </application> 40 41 </manifest>
DEMO:下载地址:http://download.csdn.net/detail/androidsj/7678947
分类:
Android系统硬件功能开发
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 智能Agent如何改造传统工作流:从搜索到全能助手