以下是一个代码示例,演示如何设置和使用NFC前台派发:
public class MainActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback {
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取NFC适配器
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// 检查设备是否支持NFC
if (nfcAdapter == null) {
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
return;
}
// 检查应用程序是否具有必需的NFC权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.NFC)
!= PackageManager.PERMISSION_GRANTED) {
// 申请NFC权限
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.NFC }, 0);
}
}
@Override
protected void onResume() {
super.onResume();
// 设置NFC前台派发
Intent nfcIntent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter[] intentFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };
String[][] techLists = new String[][] { new String[] { IsoDep.class.getName() } };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, techLists