android nfc NDEF的RTD_TEXT读写

       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();
		}


	
    	
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值