您的位置:首页 > 移动开发 > Android开发

android nfc NDEF的RTD_TEXT读写

2015-11-23 14:32 537 查看
android nfc 有两种读写模式,分别是NDEF读写模式与非NDEF读写模式,非NDEF读写模式中又有一下几种:

IsoDep、MifareClassic、MifareUltralight、Ndef、ndefFormtable、Nfca、Nfcb、NfcBarcode、NfcF、NfcV(通过Tag.getTechlist()获得)。

主要讲的是NDEF格式的读写,测试demo地址如下:

http://download.csdn.net/detail/u012303938/9292897

代码如下

package com.example.ndefreadwrite;

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

import android.support.v7.app.ActionBarActivity;
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.nfc.tech.NdefFormatable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
CheckBox checkBox1;
TextView textView1;
NfcAdapter nfcAdapter;
PendingIntent  intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox1=(CheckBox) findViewById(R.id.checkBox1);
textView1=(TextView) findViewById(R.id.textView1);
intent=PendingIntent.getActivity(this, 0, new Intent(this,getClass()), 0);
nfcAdapter=NfcAdapter.getDefaultAdapter(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
nfcAdapter.enableForegroundDispatch(this, intent, null, null);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
Toast.makeText(this, intent.getAction(), 1).show();
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())){

Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Parcelable []parcelables= intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(checkBox1.isChecked()){
NdefMessage message=getNdefTextMsg("123456789", true, true);
MyTask myTask=new MyTask(message, tag);
myTask.execute(null,null,null);
}else{
readMsg(parcelables);
}

}

}

public void readMsg(Parcelable []parcelables){
NdefMessage ndefMessages[]=null;
if(parcelables!=null){
StringBuilder builder=new StringBuilder();
ndefMessages=new NdefMessage[parcelables.length];
for(int i=0;i<parcelables.length;i++){
ndefMessages[i]=(NdefMessage) parcelables[i];
NdefRecord[] ndefRecords=ndefMessages[i].getRecords();
builder.append(readNdefRecord(ndefRecords[i]));
}
textView1.setText(builder.toString());

}else{

textView1.setText("没有信息");
}

}

public String  readNdefRecord(NdefRecord ndefRecord){
String text="";
byte[] payload=ndefRecord.getPayload();

if(ndefRecord.getTnf()==NdefRecord.TNF_WELL_KNOWN){
if(Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)){
byte staus=payload[0];
String utfType=((staus&0200)==0)?"UTF-8":"UTF-16";
int languageCodeLength=0;
languageCodeLength=staus&0077;
String langaufeCode=new String(payload,1,languageCodeLength,Charset.forName("UTF-8"));

try {
String payloadText=new String(payload,1+languageCodeLength,payload.length
-(1+languageCodeLength),utfType)	;
text="语言:"+langaufeCode+"内容:"+payloadText;
} catch (Exception e) {
// TODO: handle exception
text="解析异常";
}

}else{
text="不是RTD_TEXT";
}

}else{
text="不是TNF_WELL_KNOWN";
}

return text;
}

public void writeMsg(Parcelable parcelable[]){

}

public static NdefMessage getNdefTextMsg(String text,boolean encodeUtf8
,boolean aar){
Locale locale=new Locale("en","US");
byte [] localeBytes=locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

Charset charsetEncode=encodeUtf8?Charset.forName("UTF-8"):Charset.forName("UTF-16");
int utfBit=encodeUtf8?0:(1<<7);//128
char status=(char) (utfBit+localeBytes.length);

byte[] textBytes=text.getBytes(charsetEncode);
byte[] data=new byte[1+localeBytes.length+textBytes.length];
data[0]=(byte) status;
System.arraycopy(localeBytes, 0, data, 1, localeBytes.length);
System.arraycopy(textBytes, 0, data, localeBytes.length+1, textBytes.length);
NdefRecord ndefRecord=new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);

if(aar){
return new NdefMessage(new NdefRecord[]{
ndefRecord,NdefRecord.createApplicationRecord("com.example.ndefreadwrite")
});
}
return new NdefMessage(new NdefRecord[]{
ndefRecord
});
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {

return true;
}
return super.onOptionsItemSelected(item);
}

private class MyTask extends AsyncTask<Object, Object, Object>{
NdefMessage message;
Tag tag;
String text="";

public MyTask(NdefMessage message,Tag tag) {
// TODO Auto-generated constructor stub
this.message=message;
this.tag=tag;
}

@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
int size=message.toByteArray().length;
try {
Ndef ndef=Ndef.get(tag);
if(ndef==null){
NdefFormatable formatable=NdefFormatable.get(tag);
if(formatable!=null){
try {
formatable.connect();
try {
formatable.format(message);
} catch (Exception e) {
// TODO: handle exception
text="格式化失败";
}

} catch (Exception e) {
// TODO: handle exception
text="格式化连接失败";
}finally{
formatable.close();
}
}else{
text="这不是ndef标签,不能格式化";
}
}else{
ndef.connect();
try {
if(!ndef.isWritable()){
text="该ndef标签不能写入";
}else if(ndef.getMaxSize()<size){
text="内存不够";
}else{
ndef.writeNdefMessage(message);
text="写入成功";
}
} catch (Exception e) {
// TODO: handle exception
text="ndef连接失败";
}finally{
ndef.close();
}
}
} catch (Exception e) {
// TODO: handle exception
text="这不是ndef标签";
}

return text;
}

@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: