NFC(7)向NFC硬件写入数据的两个示例(nfc硬件启动android应用,nfc硬件打开uri)

向NFC标签写入数据基本步骤

1,获取Tag对象

  Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

2,判断NFC标签的数据类型(通过Ndef.get方法)

  Ndef ndef = Ndef.get(tag);

3,NFC开始连接

  ndef.connect();

4,建NdefMessage数据,然后将它写入数据
  ndef.writeNdefMessage(ndefMessage); 

示例1: nfc标签设备启动android应用

  1 import android.app.Activity;
  2 import android.app.PendingIntent;
  3 import android.content.Intent;
  4 import android.nfc.NdefMessage;
  5 import android.nfc.NdefRecord;
  6 import android.nfc.NfcAdapter;
  7 import android.nfc.Tag;
  8 import android.nfc.tech.Ndef;
  9 import android.os.Bundle;
 10 import android.view.View;
 11 import android.widget.Button;
 12 import android.widget.Toast;
 13 
 14 public class RunApplicationActivity extends Activity {
 15 
 16     private Button mSelectAutoRunApplication;
 17     private String mPackageName;
 18     
 19     
 20     private NfcAdapter mNfcAdapter;//用来NFC通信
 21     private PendingIntent mPendingIntent;//用来封装当前窗口
 22 
 23     @Override
 24     protected void onCreate(Bundle savedInstanceState) {
 25         super.onCreate(savedInstanceState);
 26         setContentView(R.layout.activity_auto_run_application);
 27 
 28         mSelectAutoRunApplication = (Button) findViewById(R.id.button_select_auto_run_application);
 29 
 30         mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
 31         mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
 32                 getClass()), 0);
 33 
 34     }
 35     //从另一个aty中取出数据.
 36     @Override
 37     protected void onActivityResult(int requestCode, int resultCode, Intent data)
 38     {
 39         if (resultCode == 1)
 40         {
 41             mSelectAutoRunApplication.setText(data.getExtras().getString(
 42                     "package_name"));
 43             String temp = mSelectAutoRunApplication.getText().toString();
 44             mPackageName = temp.substring(temp.indexOf("\n") + 1);
 45             
 46         }
 47 
 48     }
 49     //由于在manifest.xml中指定当前aty主singleTop,所以startactivity时 onCreate只被调用一次.
 50     //但是onNewIntent在startactivity会被调用
 51     @Override
 52     public void onNewIntent(Intent intent) {
 53         if (mPackageName == null)
 54             return;
 55 
 56         //第1步,取得NFC 标签
 57         Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
 58 
 59         writeNFCTag(detectedTag);//自写的成员函数
 60     }
 61 
 62     //第4种 过滤方法的开始函数,要比3种过滤方法优先级高
 63     @Override
 64     public void onResume() {
 65         super.onResume();
 66         //在Resume时让当前窗口优先处理nfc数据
 67         if (mNfcAdapter != null){
 68             mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
 69                     null);
 70         }
 71     }
 72     //第4种 过滤方法结束函数,要比3种过滤方法优先级高
 73     @Override
 74     public void onPause() {
 75         super.onPause();
 76         //在onPause时取消让当前窗口优先处理nfc数据
 77         if (mNfcAdapter != null)
 78             mNfcAdapter.disableForegroundDispatch(this);
 79     }
 80     public void onClick_SelectAutoRunApplication(View view)
 81     {
 82         Intent intent = new Intent(this, InstalledApplicationListActivity.class);
 83         startActivityForResult(intent, 0);
 84     }
 85     //向nfc标签写入数据的函数
 86     public void writeNFCTag(Tag tag) {
 87         if (tag == null) {
 88             return;
 89         }
 90         try {
 91             //第2步,判断NFC标签的数据类型(通过Ndef.get方法)
 92             Ndef ndef = Ndef.get(tag);
 93             
 94             if(ndef != null )
 95             {
 96                 //第3步,NFC开始连接
 97                 ndef.connect();
 98                 
 99                 if(!ndef.isWritable())//标签是否可写.
100                 {
101                     return;
102                 }
103                 //第4步,准备数据
104                 //一个NdefMessage 中可有多个NdefRecord,它们之间关系类似table与record
105                 NdefMessage ndefMessage = new NdefMessage(
106                         new NdefRecord[] { NdefRecord
107                                 .createApplicationRecord(mPackageName) });
108                 int size = ndefMessage.toByteArray().length;
109                 if(ndef.getMaxSize() < size)
110                 {
111                     return;
112                 }
113                 //第5步,把数据写入到nfc标签中.
114                 ndef.writeNdefMessage(ndefMessage);
115                 //第6步,写入成功提示
116                 Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
117             }
118         } catch (Exception e) {
119             //有可能异常
120             e.printStackTrace();
121         }
122     }
123 }

 

manifest.xml

 1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 2     package="c.e.run.application"
 3     android:versionCode="1"
 4     android:versionName="1.0" >
 5 
 6     <uses-sdk
 7         android:minSdkVersion="15"
 8         android:targetSdkVersion="15" />
 9 
10     <uses-permission android:name="android.permission.NFC" />
11 
12     <application
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".RunApplicationActivity"
18             android:label="@string/title_activity_auto_run_application"
19             android:launchMode="singleTop"
20             android:screenOrientation="portrait" >
21             <intent-filter>
22                 <action android:name="android.intent.action.MAIN" />
23                 <category android:name="android.intent.category.LAUNCHER" />
24             </intent-filter>
25         </activity>
26         <activity
27             android:name=".InstalledApplicationListActivity"
28             android:label="@string/title_activity_installed_application_list"
29             android:screenOrientation="portrait" />
30 
31     </application>
32 
33 </manifest>

 

示例2: nfc标签设备打开一个uri

 1 import android.app.Activity;
 2 import android.app.PendingIntent;
 3 import android.content.Intent;
 4 import android.net.Uri;
 5 import android.nfc.NdefMessage;
 6 import android.nfc.NdefRecord;
 7 import android.nfc.NfcAdapter;
 8 import android.nfc.Tag;
 9 import android.nfc.tech.Ndef;
10 import android.nfc.tech.NdefFormatable;
11 import android.os.Bundle;
12 import android.widget.Toast;
13 
14 public class AutoOpenUriActivity extends Activity {
15     private NfcAdapter nfcAdapter;
16     private PendingIntent pendingIntent;
17 
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21 
22         setContentView(R.layout.activity_auto_open_uri);
23         nfcAdapter = NfcAdapter.getDefaultAdapter(this);
24         pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
25                 getClass()), 0);
26 
27     }
28 
29     @Override
30     public void onResume() {
31         super.onResume();
32         if (nfcAdapter != null)
33             nfcAdapter
34                     .enableForegroundDispatch(this, pendingIntent, null, null);
35     }
36 
37     @Override
38     public void onNewIntent(Intent intent) {
39         //第1步,取得NFC 标签
40         Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
41         writeNFCTag(detectedTag);
42     }
43 
44     @Override
45     public void onPause() {
46         super.onPause();
47         if (nfcAdapter != null)
48             nfcAdapter.disableForegroundDispatch(this);
49 
50     }
51 
52     public void writeNFCTag(Tag tag) {
53         if (tag == null) {
54             return;
55         }
56         Uri uri = Uri.parse("http://www.bing.com");
57         NdefMessage ndefMessage = new NdefMessage(
58                 new NdefRecord[] { NdefRecord.createUri(uri) });
59         int size = ndefMessage.toByteArray().length;
60         try{
61             Ndef ndef = Ndef.get(tag);
62             
63             if (ndef != null){// 已经格式化
64                 ndef.connect();
65                 if (!ndef.isWritable()) {
66                     return;
67                 }
68                 if (ndef.getMaxSize() < size) {
69                     return;
70                 }
71                 ndef.writeNdefMessage(ndefMessage);
72                 Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
73             } else {// 标签未格式化
74                     // 第1步,获取NdefFormatable
75                 NdefFormatable format = NdefFormatable.get(tag);
76                 if (format != null){// 可以格式化
77                     // 第2步,连接
78                     format.connect();
79                     // 第3步,格式化同时把数据写入到标签中.
80                     format.format(ndefMessage);
81                     Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
82                 } else {// 不可格式化
83                     Toast.makeText(this, "formating is failed",
84                             Toast.LENGTH_LONG).show();
85                 }
86             }
87             
88         } catch (Exception e) {
89             e.printStackTrace();
90         }
91     }
92 
93 }

 

posted @ 2015-09-04 19:05  f9q  阅读(2464)  评论(0编辑  收藏  举报