码迷,mamicode.com
首页 > 其他好文 > 详细

NFC之读写NFC标签的文本

时间:2015-01-16 22:23:50      阅读:459      评论:0      收藏:0      [点我收藏+]

标签:android   java   nfc   

         继上一篇整理了NFC之让Android自动运行程序,这一篇整理一下读写NFC标签的文本

开始之前大概思路如下

技术分享


        对于NDEF文本格式来说。这些数据的第1个字节描述了数据的状态,然后若干个字节描述文本的语言编码,最后剩余字节表示文本数据。这些数据格式由NFC Forum的相关规范定义,可以从下面的地址下载相关的规范 

NDEF文本数据格式:
技术分享
状态字节编码格式:
技术分享
根据以上信息可以开始code
新建Activity
package com.cayden.read.write.text;

import java.nio.charset.Charset;
import java.util.Locale;


import android.app.Activity;
import android.app.PendingIntent;
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;
import android.widget.Toast;

public class ReadWriteTextMainActivity extends Activity {
	
	private TextView mInputText;
	private String mText;

	private NfcAdapter mNfcAdapter;
	private PendingIntent mPendingIntent;
	@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);
		
		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()), 0);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode == 1) {
			mText = data.getStringExtra("text");
			mInputText.setText(mText);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mNfcAdapter != null)
			mNfcAdapter.disableForegroundDispatch(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mNfcAdapter != null)
			mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
					null);
	}

	public void onNewIntent(Intent intent) {
		Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();
		// read nfc text
		if (mText == null) {
			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;
	}
	/**
	 * 往nfc标签写入数据
	 * @param ndefMessage
	 * @param tag
	 * @return
	 *
	 */
	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;

	}
	
	public void onClick_InputText(View view)
	{
		Intent intent = new Intent(this, InputTextActivity.class);
		startActivityForResult(intent, 1);
	}

}

然后创建一个读取内容的Activity

package com.cayden.read.write.text;

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;

public class ShowNFCTagContentActivity extends Activity {

	private TextView mTagContent;
	private Tag mDetectedTag;
	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之读写NFC标签的文本

标签:android   java   nfc   

原文地址:http://blog.csdn.net/cuiran/article/details/42784837

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!