NFC技术:让Android⾃动打开⽹页 1//实现⾃动打开⽹页
2//程序包含NFC的格式化,和向NFC写⼊数据
3//程序运⾏好后,将NFC标签放在⼿机背部,。。弹出toast后,关闭程序,再将NFC标签放在⼿机背部实现⾃动打开百度⽹页
4public class AutoOpenUriActivity extends Activity {
5private NfcAdapter nfcAdapter;
6private PendingIntent pendingIntent;
7 String url = "www.baidu";
8
9 @Override
10protected void onCreate(Bundle savedInstanceState) {
12 setContentView(R.layout.fragment_main);
13 nfcAdapter = DefaultAdapter(this);
14 pendingIntent = Activity(this, 0, new Intent(this,
15 getClass()), 0);
16
17 }
18
19 @Override
20protected void onResume() {
21// TODO Auto-generated method stub
23// 获得焦点,设置这个窗⼝优先级⾼于所有可以处理NFC的窗⼝
24if (nfcAdapter != null) {
25 nfcAdapter
26 .enableForegroundDispatch(this, pendingIntent, null, null);
27
28 }
29 }
30
31 @Override
32protected void onPause() {
33// TODO Auto-generated method stub
34
36// 程序退出,窗⼝恢复默认
37if (nfcAdapter != null) {
38 nfcAdapter.disableForegroundDispatch(this);
39 }
40 }
41
网页自动关闭42 @Override
43protected void onNewIntent(Intent intent) {
44// 当清单⽂件中设置为"singleTop"时,oncreate()只调⽤⼀次,⽽onNewIntent()每次调⽤
45// TODO Auto-generated method stub
47
48// 第⼀步获得Tag
49 Tag detectedTag = ParcelableExtra(NfcAdapter.EXTRA_TAG);
50// 第⼆步写⼊标签
51 writeNFCTag(detectedTag);
52
53 }
54
55private void writeNFCTag(Tag tag) {
56// TODO Auto-generated method stub
57
58if (tag == null) {
59return;
60 }
61 NdefMessage ndefMessage = new NdefMessage(
62new NdefRecord[] { ateUri(Uri.parse(url)) });
63int size = ByteArray().length;
64try {
65 Ndef ndef = (tag);
66if (ndef != null) {
67 t();
68// 是否⽀持可写
69if (!ndef.isWritable()) {
70return;
71
72 }
73// 判断是否可以容纳要写⼊的数据
74if (MaxSize() < size) {
75return;
76 }
77 ndef.writeNdefMessage(ndefMessage);
78 Toast.makeText(this, "NFC成功写⼊", 0).show();
79 } else {
80// 新买的NFC需要格式化---》格式化NFSC
81 NdefFormatable format = (tag);
82if (format != null) {
83 t();
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 }
发布评论