1 //向nfc标签读写MifareUltraligh格式的数据 2 public class MainActivity extends Activity { 3 private CheckBox mwriteData; 4 private NfcAdapter mNfcAdapter; 5 private PendingIntent mPendingIntent; 6 7 @Override 8 protected void onCreate(Bundle savedInstanceState) { 9 super.onCreate(savedInstanceState); 10 setContentView(R.layout.fragment_main); 11 12 mwriteData = (CheckBox) findViewById(R.id.checkBox1); 13 mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 14 mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 15 getClass()), 0); 16 } 17 18 @Override 19 protected void onNewIntent(Intent intent) { 20 // TODO Auto-generated method stub 21 super.onNewIntent(intent); 22 Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 23 24 String[] techList = tag.getTechList(); 25 boolean haveMifareUltralight = false; 26 for (String tech : techList) { 27 if (tech.indexOf("MifareUltralight") >= 0) { 28 haveMifareUltralight = true; 29 break; 30 } 31 32 } 33 if (!haveMifareUltralight) { 34 Toast.makeText(this, "不支持MifareUltralight格式数据", 0).show(); 35 return; 36 } 37 // 选中为写数据 38 if (mwriteData.isChecked()) { 39 writeTag(tag); 40 41 } 42 // 否则为读数据 43 else { 44 String data = readTag(tag); 45 if (data != null) { 46 Toast.makeText(this, data, 0).show(); 47 } 48 } 49 50 } 51 52 @Override 53 protected void onResume() { 54 // TODO Auto-generated method stub 55 super.onResume(); 56 if (mNfcAdapter != null) { 57 mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, 58 null); 59 } 60 } 61 62 @Override 63 protected void onPause() { 64 // TODO Auto-generated method stub 65 super.onPause(); 66 if (mNfcAdapter != null) { 67 mNfcAdapter.disableForegroundDispatch(this); 68 } 69 } 70 71 // 向nfc标签写MifareUltralight格式数据 72 public void writeTag(Tag tag) { 73 MifareUltralight ultralight = MifareUltralight.get(tag); 74 try { 75 ultralight.connect(); 76 ultralight.writePage(4, "中国".getBytes(Charset.forName("GB2312"))); 77 ultralight.writePage(5, "美国".getBytes(Charset.forName("GB2312"))); 78 ultralight.writePage(6, "韩国".getBytes(Charset.forName("GB2312"))); 79 ultralight.writePage(7, "日本".getBytes(Charset.forName("GB2312"))); 80 81 Toast.makeText(this, "写入MifareUltralight格式数据成功", 0).show(); 82 } catch (Exception e) { 83 // TODO: handle exception 84 } finally { 85 try { 86 ultralight.close(); 87 } catch (IOException e) { 88 // TODO Auto-generated catch block 89 e.printStackTrace(); 90 } 91 } 92 } 93 94 public String readTag(Tag tag) { 95 MifareUltralight ultralight = MifareUltralight.get(tag); 96 try { 97 ultralight.connect(); 98 byte[] data = ultralight.readPages(4); 99 return new String(data, Charset.forName("GB2312")); 100 101 } catch (Exception e) { 102 // TODO: handle exception 103 } finally { 104 105 try { 106 ultralight.close(); 107 } catch (IOException e) { 108 // TODO Auto-generated catch block 109 e.printStackTrace(); 110 } 111 112 } 113 return null; 114 115 } 116 }
原文:http://www.cnblogs.com/my334420/p/6914668.html