1 //实现自动打开网页 2 //程序包含NFC的格式化,和向NFC写入数据 3 //程序运行好后,将NFC标签放在手机背部,。。弹出toast后,关闭程序,再将NFC标签放在手机背部实现自动打开百度网页 4 public class AutoOpenUriActivity extends Activity { 5 private NfcAdapter nfcAdapter; 6 private PendingIntent pendingIntent; 7 String url = "https://www.baidu.com"; 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.fragment_main); 13 nfcAdapter = NfcAdapter.getDefaultAdapter(this); 14 pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 15 getClass()), 0); 16 17 } 18 19 @Override 20 protected void onResume() { 21 // TODO Auto-generated method stub 22 super.onResume(); 23 // 获得焦点, 设置这个窗口优先级高于所有可以处理NFC的窗口 24 if (nfcAdapter != null) { 25 nfcAdapter 26 .enableForegroundDispatch(this, pendingIntent, null, null); 27 28 } 29 } 30 31 @Override 32 protected void onPause() { 33 // TODO Auto-generated method stub 34 35 super.onPause(); 36 // 程序退出,窗口恢复默认 37 if (nfcAdapter != null) { 38 nfcAdapter.disableForegroundDispatch(this); 39 } 40 } 41 42 @Override 43 protected void onNewIntent(Intent intent) { 44 // 当清单文件中设置为"singleTop"时,oncreate()只调用一次,而onNewIntent()每次调用 45 // TODO Auto-generated method stub 46 super.onNewIntent(intent); 47 48 // 第一步获得Tag 49 Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 50 // 第二步写入标签 51 writeNFCTag(detectedTag); 52 53 } 54 55 private void writeNFCTag(Tag tag) { 56 // TODO Auto-generated method stub 57 58 if (tag == null) { 59 return; 60 } 61 NdefMessage ndefMessage = new NdefMessage( 62 new NdefRecord[] { NdefRecord.createUri(Uri.parse(url)) }); 63 int size = ndefMessage.toByteArray().length; 64 try { 65 Ndef ndef = Ndef.get(tag); 66 if (ndef != null) { 67 ndef.connect(); 68 // 是否支持可写 69 if (!ndef.isWritable()) { 70 return; 71 72 } 73 // 判断是否可以容纳要写入的数据 74 if (ndef.getMaxSize() < size) { 75 return; 76 } 77 ndef.writeNdefMessage(ndefMessage); 78 Toast.makeText(this, "NFC成功写入", 0).show(); 79 } else { 80 // 新买的NFC需要格式化---》格式化NFSC 81 NdefFormatable format = NdefFormatable.get(tag); 82 if (format != null) { 83 format.connect(); 84 format.format(ndefMessage);// 既格式化了又写入内容 85 Toast.makeText(this, "NFC成功格式化", 0).show(); 86 } else { 87 Toast.makeText(this, "NFC格式化失败", 0).show(); 88 } 89 90 } 91 } catch (Exception e) { 92 // TODO: handle exception 93 } 94 } 95 96 }