2011年9月22日 星期四

[Android] NFC API的使用

Android 在2.3.3以後 加入了NFC 的功能 . NFC是什麼呢?
NFC是Near Field Communication 的縮寫. 簡單的講類似RFID的東東 , 是種近距離(10cm以下) 的contectless 的讀取技術。
 不過NFC 主要有三種模式 : Reader Mode (當讀卡機), Card Mode (變成卡片,讓別人讀) , Peer to Peer Mode (P2P,雙方互相傳送資料) 詳細的內容請參閱google大神。
今天主要的是簡單講解一下 Android 上的 NFC如何使用 在Android 系統上 NFC是否開啓的控制是在 設定->無線與網路->NFC。
在Android中的NFC 有一個觀念 只要NFC服務被開啓,
他就會在背景去監測是否有感應 ,就很像短訊或電話ㄧ樣,會去等待有沒有人傳送訊號過來 在Android上你不需要去管他怎樣去偵測到的,
只需要專著在收到系統發出的NFC Intent 之後要如何去處理就可以了,
不需要去管NFC Device初始化那些問題 ,當收到了Android系統發出的NFC Intent,他會先去檢查是否有註冊為NFC程式的APP,如果有會POP出選單 讓使用者決定要用哪隻APP去開啓 ?
這就是所謂的 Using the intent dispatch system 要如何註冊我的APP是NFC程式呢?
首先要先開起AndroidManifest.xml
        
            
                
                
            

            
                                    
                      
            
                                                     
            
               
                    
        
而記得在此xml要去permission 把NFC權限開啓 nfc_tech_filter.xml裡面則是定義了 這隻程式可以接受TAG的規格 可以從以下這幾挑選

    
        android.nfc.tech.IsoDep
        android.nfc.tech.NfcA        
        android.nfc.tech.NfcB
        android.nfc.tech.NfcF
        android.nfc.tech.NfcV
        android.nfc.tech.Ndef
        android.nfc.tech.NdefFormatable
        android.nfc.tech.MifareClassic
        android.nfc.tech.MifareUltralight
    

這樣定義完之後就算配制完成,當程式啓動後我們就可以用getIntent() 去取得這個Intent的相關資料。
做到這邊 大家可能會有個問題就是:假如我不想在執行APP的時候 又會跳出NFC Menu ,而是我偵測到NFC標籤(TAG)時 交給程式自動去處理呢?
這時就要另外一種操作NFC的方式 - Using the foreground dispatch system 
透過這種方式,當NFC標籤被偵測到會傳遞Intent過來,程式可優先把NFC Intent抓下來處理 而不交給 Android的系統的dispatch system。
其使用方式如下
 1.要先在onCreate()裡面定義和宣告這隻Activity所接收的Intent和標籤格式
    try {
   NfcManager manager =(NfcManager)getSystemService(NFC_SERVICE); 
   mAdapter = manager.getDefaultAdapter( );     
   mPendingIntent = PendingIntent.getActivity( 
        this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);       
   IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); 
   mFilters = new IntentFilter[] { 
           ndef, 
   };         
   mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
  } catch (Exception e) {
   e.printStackTrace();
  }

2.而在 onResume() 宣告如下:
    protected void onResume() {
     super.onResume();
  mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
    }
3.在onPause()宣告如下
   protected void onPause() {
 super.onPause();
 mAdapter.disableForegroundDispatch(this );
以上就算是配置完成了,以後這隻程式就有能力優先處理NFC Intent 接下來會問收到的NFC Intent在哪裡處理 答案就是在onNewIntent
public void onNewIntent(Intent intent){
 
// 做你想做的處理

}
詳細的讀取、寫入、Peer to Peer傳輸 請參考 http://developer.android.com/guide/topics/nfc/index.html

另外onNewIntent在執行的時候,雖然畫面看不出來,但其實主Activity會被拉到背景進入onPause()然後執行完很快的又回到 onResume()

沒有留言:

張貼留言