Android NFC讀取卡片的ID

本文轉(zhuǎn)自薄呵呵的文章

初始化適配器 NfcAdapter PendingIntent

Intent nfcIntent = new Intent(this, getClass()); 
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
mAdapter = NfcAdapter.getDefaultAdapter(this); 
mPendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
 String infoText = "看下這個支持nfc嗎 或者 開了沒"; 
 if (mAdapter == null) { 
      Toast.makeText(getApplicationContext(), 
      infoText, Toast.LENGTH_SHORT).show(); 
 } 

重寫onNewIntent()方法

 @Override 
 protected void onNewIntent(Intent intent) { 
 Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 

 //獲取 Tag 讀取 ID 得到字節(jié)數(shù)組 轉(zhuǎn)字符串 轉(zhuǎn)碼 得到卡號(默認(rèn)16進(jìn)制 這請自便)
 Long cardNo = Long.parseLong(flipHexStr(ByteArrayToHexString(tag.getId())), 16); 
 // if (cardNo.toString().getBytes().length == 10) { 
 num = cardNo.toString();
  // } else {
   // 轉(zhuǎn)的時候有個地方需要注意下 如果開頭為零的話 會省略所以位數(shù)會改變 
   // num = "0" + cardNo.toString(); 
   // } 
   TextView textView = (TextView) findViewById(R.id.nfc_text); 
   textView.setText(num); 
   Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
}

息屏之類的操作

@Override 
public void onPause() {
 super.onPause();
  if (mAdapter != null) { 
  mAdapter.disableForegroundDispatch(this); 
  } 
  } 
@Override
 public void onResume() { 
 super.onResume(); 
 mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null); 
 }

最后附上轉(zhuǎn)碼工具類

public class ByteArrayTohexHepler {

    public static String flipHexStr(String s) { 
      StringBuilder result = new StringBuilder(); 
      for (int i = 0; i <= s.length() - 2; i = i + 2) { 
     result.append(new StringBuilder(s.substring(i, i + 2)).reverse()); 
 } 
   return result.reverse().toString();
} 
  
  // 16轉(zhuǎn)10進(jìn)制 
  public static String ByteArrayToHexString(byte[] inarray) { 
  int i, j, in; 
  String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; 
  StringBuilder out = new StringBuilder();
  
   for (j = 0; j < inarray.length; ++j) {
    in = (int) inarray[j] & 0xff; 
    i = (in >> 4) & 0x0f; 
   out.append(hex[i]); 
   i = in & 0x0f; 
   out.append(hex[i]); 
   } return out.toString(); 
 } 
}

大家有什么問題可以在下方留言

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容