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 }