Android NFC讀取卡片的ID

本文轉自薄呵呵的文章

初始化適配器 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 得到字節數組 轉字符串 轉碼 得到卡號(默認16進制 這請自便)
 Long cardNo = Long.parseLong(flipHexStr(ByteArrayToHexString(tag.getId())), 16); 
 // if (cardNo.toString().getBytes().length == 10) { 
 num = cardNo.toString();
  // } else {
   // 轉的時候有個地方需要注意下 如果開頭爲零的話 會省略所以位數會改變 
   // 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); 
 }

最後附上轉碼工具類

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轉10進制 
  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(); 
 } 
}

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章