2016-07-30 104 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对象,因此也无法与标签进行通信。

因此,您无法对此做任何事情。您只能尝试重新阅读标签(通过将其与手机放在一起)。