安卓 nfc 监听 完整的java代码
时间: 2024-09-07 15:01:54 浏览: 16
在Android中,监听NFC(近场通信)通常涉及创建`NfcAdapter`、`PendingIntent`和注册`BroadcastReceiver`。以下是一个简单的Java代码示例,展示了如何监听NDEF(NFC数据交换格式)标签的检测:
```java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Parcelable;
public class NfcListener {
private static final String ACTION_TAG_DETECTED = "com.example.TAG_DETECTED";
private final NfcAdapter nfcAdapter;
private BroadcastReceiver receiver;
public NfcListener(Context context) {
nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter == null) {
throw new RuntimeException("NFC is not supported on this device.");
}
// Register the receiver to listen for tag detections
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (detectedTag != null) {
handleDetectedTag(detectedTag);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED); // Listen for tag detection
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED); // Or NDEF message detection
// Enable foreground dispatch for receiving tags while app is in focus
enableForegroundDispatch(context);
}
private void enableForegroundDispatch(Context context) {
Intent intent = new Intent(context, getClass()); // Same activity that's handling this
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// Specify data format(s) you want to receive
byte[][] techLists = {NfcA.class.getName().getBytes(), Ndef.class.getName().getBytes()};
nfcAdapter.enableForegroundDispatch(
context, // Context
pendingIntent, // Pending Intent
techLists, // Tech lists
null // No custom payload
);
}
private void handleDetectedTag(Tag tag) {
// Read and process NDEF messages from the tag here
NdefMessage message = NdefReader.read(tag);
if (message != null) {
// Do something with the message, e.g., parse it or store it
logAndProcessMessage(message);
} else {
log("No NDEF message found in tag.");
}
}
private void log(String message) {
Log.d("NFC", message);
}
private void logAndProcessMessage(NdefMessage message) {
// Process your NDEF message logic here
// For example, decode it into a string or save it to local storage
// After processing, you can send an event or notification as needed
}
public void unregisterReceiver() {
if (receiver != null) {
context.unregisterReceiver(receiver);
receiver = null;
}
}
}
```
在使用这段代码之前,别忘了在AndroidManifest.xml中添加NFC权限:
```xml
<uses-permission android:name="android.permission.NFC" />
```