2016-07-30 124 views
0

我做了一個讀取NFC標籤的應用程序,但是我面臨的問題是並非所有的頻段都有ID。Android將ID寫入空NFC標籤

是否可以將新ID分配給空標籤?

private String tagInfoId = ""; 
private NfcAdapter nfcAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.dialog_player); 
    if (!userPrefs.isLoggedIn().get()) finish(); 
    trackerService = ServiceGateway.createAuthorizedService(TrackerService.class); 

    nfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    if (nfcAdapter == null) { 
     Toast.makeText(this, 
       "NFC NOT supported on this devices!", 
       Toast.LENGTH_LONG).show(); 
     finish(); 
    } else if (!nfcAdapter.isEnabled()) { 
     Toast.makeText(this, 
       "NFC NOT Enabled!", 
       Toast.LENGTH_LONG).show(); 
     finish(); 
    } 
} 

@Override 
protected void onResume() { 
    super.onResume(); 

    Intent intent = getIntent(); 
    String action = intent.getAction(); 
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { 
     Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
     if (tag == null) { 
      Log.d(TAG, "tag == null"); 

      //here is possible to write a new tag code ??? 

     } else { 
      byte[] tagId = tag.getId(); 
      for (int i = 0; i < tagId.length; i++) { 
       tagInfoId += Integer.toHexString(tagId[i] & 0xFF); 
      } 
      Log.d(TAG, "onResume() called with: " + "tagID:" + tagInfoId); 

     } 
    } 
} 

的Manifest.xml

<activity 
      android:name=".activities.NfcActivity" 
      android:noHistory="true" 
      android:theme="@android:style/Theme.Translucent.NoTitleBar"> 
      <intent-filter> 
       <action android:name="android.nfc.action.TAG_DISCOVERED" /> 
       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </activity> 

另外,如果我分配一個ID到一個新的標籤,它會以同樣的方式閱讀或做我必須改變上面的代碼?

回答

0

對於NFC意圖,意圖額外的TAG絕不能爲空(或null)。因此,您應始終從intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)獲得一個Tag對象,並且您絕對不應該分支到if (tag == null) {

如果您仍然到達tag == null分支,那麼這與該標籤沒有標識符無關。這意味着您的設備的NFC堆棧中發生了嚴重錯誤。例如,這可能是標籤閱讀在很早的階段被中斷,或者標籤沒有正確說出讀者期望的協議。由於您沒有收到Tag對象,因此也無法與標籤進行通信。

因此,您無法對此做任何事情。您只能嘗試重新閱讀標籤(通過將其與手機放在一起)。