要在Android模拟器上模拟NFC功能,可以使用HCE(Host Card Emulation)技术。以下是一种解决方法的代码示例:
import android.nfc.cardemulation.HostApduService;
import android.os.Bundle;
import android.util.Log;
public class NfcService extends HostApduService {
private static final String TAG = NfcService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "NFC service created");
}
@Override
public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) {
// 处理NFC命令
Log.d(TAG, "Received command APDU: " + ByteArrayToHexString(commandApdu));
// 返回模拟的NFC响应
byte[] responseApdu = new byte[]{(byte) 0x90, (byte) 0x00};
Log.d(TAG, "Sending response APDU: " + ByteArrayToHexString(responseApdu));
return responseApdu;
}
@Override
public void onDeactivated(int reason) {
Log.d(TAG, "NFC deactivated: " + reason);
}
// 将字节数组转换为十六进制字符串
private String ByteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, null, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
IsoDep isoDep = IsoDep.get(tag);
try {
isoDep.connect();
byte[] commandApdu = new byte[]{(byte) 0x00, (byte) 0xA4, (byte) 0x04, (byte) 0x00, (byte) 0x07, (byte) 0xF0, (byte) 0x01,