NFC(Near Field Communication,近场通信)是一种短距离的高频无线通信技术,允许电子设备之间进行非接触式点对点数据传输。在Android开发中,可以使用NFC功能来读取NFC标签或卡片的信息,例如获取卡号。
以下是在Android Studio中使用NFC获取卡号的基本步骤和示例代码:
在AndroidManifest.xml
文件中添加NFC权限:
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
创建一个Activity来处理NFC标签的读取事件:
public class NFCReaderActivity extends AppCompatActivity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private IntentFilter[] intentFiltersArray;
private String[][] techListsArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_reader);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// 设备不支持NFC
finish();
return;
}
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndefIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefIntent.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
intentFiltersArray = new IntentFilter[] { ndefIntent };
techListsArray = new String[][] { new String[] { NfcA.class.getName() } };
}
@Override
protected void onResume() {
super.onResume();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
}
// 处理NDEF消息
processNdefMessages(messages);
}
}
}
private void processNdefMessages(NdefMessage[] messages) {
for (NdefMessage message : messages) {
for (NdefRecord record : message.getRecords()) {
byte[] payload = record.getPayload();
String cardNumber = new String(payload, StandardCharsets.UTF_8).trim();
// 处理卡号
Log.d("NFCReader", "Card Number: " + cardNumber);
}
}
}
}
通过以上步骤和代码示例,可以在Android应用中实现NFC卡号的读取功能。
领取专属 10元无门槛券
手把手带您无忧上云