Android NFC无接触支付是使用近场通讯(NFC)技术进行的。具体而言,当用户将NFC手机靠近装有NFC读卡器的支付终端时,NFC芯片将使用短距离电磁波进行通信,以在两个设备之间建立连接。一旦连接建立,支付终端将要求用户输入密码或使用指纹确认支付。一旦支付已经验证,支付终端将从用户的指定银行账户中扣除付款金额。
以下是一个简单的代码示例,展示如何实现基于NFC的支付:
// 检查设备是否支持NFC if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) { Toast.makeText(this, "NFC not supported by device", Toast.LENGTH_LONG).show(); return; }
// 如果用户还没有启用NFC,则询问他们是否要启用 if (!nfcAdapter.isEnabled()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("NFC not enabled"); builder.setMessage("Do you want to enable NFC?"); builder.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS)); } }); builder.setNegativeButton("No", null); builder.show(); }
// 创建一个PendingIntent等待NFC标签扫描 PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// 创建一个IntentFilter以侦听NFC标签的扫描 IntentFilter[] filters = new IntentFilter[]{ new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED), };
// 创建一个TechList,定义我们需要检查哪些标签技术 String[][] techLists = new String[][]{ new String[]{NfcA.class.getName()}, };
// 为NFC标签扫描设置新的Intent和IntentFilters nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techLists);
// 当NFC标签被扫描时,onNewIntent()方法将被调用 @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent);
// 从NFC标签的intent中获取数据
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msgs[] = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
// 处理标签扫描,验证支付并从银行账户中扣款
// ...
}