Android NFC编程
时间: 2023-11-03 09:15:20 浏览: 112
Android NFC编程可以使用Android SDK中提供的NFC API,具体步骤如下:
1. 在AndroidManifest.xml文件中添加NFC权限
```
<uses-permission android:name="android.permission.NFC"/>
```
2. 在Activity中注册NFC事件
```
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
filter.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, null);
}
@Override
protected void onPause() {
super.onPause();
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
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];
}
String text = new String(messages[0].getRecords()[0].getPayload());
// 处理接收到的NFC数据
}
}
}
```
3. 在Activity中发送NFC数据
```
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
NdefMessage message = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", "Hello, world!".getBytes())});
nfcAdapter.setNdefPushMessage(message, this);
```
使用以上步骤可以实现Android NFC编程。
阅读全文