要实现“触碰即付的NFC卡到手机”的功能,需要在手机端编写相应的代码来处理NFC卡的读取和支付操作。以下是一个基本的代码示例,演示了如何通过NFC技术实现触碰即付功能:
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// NFC not supported on this device
Toast.makeText(this, "NFC not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!nfcAdapter.isEnabled()) {
// NFC is disabled on this device, prompt user to enable it
Toast.makeText(this, "Please enable NFC", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
finish();
return;
}
}
@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[]{};
String[][] techListArray = new String[][]{
{IsoDep.class.getName()}
};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListArray);
}
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag != null) {
// NFC tag detected, process the payment
IsoDep isoDep = IsoDep.get(tag);
// Perform payment transaction using isoDep object
// ...
Toast.makeText(this, "Payment successful", Toast.LENGTH_SHORT).show();
}
}
}
上述代码中,首先在onCreate()
方法中检查设备是否支持NFC功能,如果不支持则退出应用。如果设备支持NFC,但未启用NFC功能,则提示用户启用NFC并跳转到系统设置界面。
在onResume()
方法中,创建一个PendingIntent
和一个空的IntentFilter
数组,并将IsoDep技术添加到技术列表中。然后通过nfcAdapter.enableForegroundDispatch()
方法启用前台调度,以确保应用在前台时能够接收到NFC相关的意图。
在onPause()
方法中,通过nfcAdapter.disableForegroundDispatch()
方法禁用前台调度,以便在应用不在前台时不会接收到NFC相关的意图。
最后,在onNewIntent()
方法中获取到NFC卡片的标签并将其转换为IsoDep
对象,然后可以使用该对象执行支付交易的逻辑。在本示例中,只是简单地显示一个支付成功的提示。
请注意,由于NFC卡的读取和支付操作涉及到与支付网关或第三方服务进行通信,因此实际的支付逻辑和代码可能更加复杂,并且可能需要集成相应的支付SDK或API。上述代码示例只是演示了基本的NFC卡读取和支付处理流程。