您可以使用onNewIntent方法来处理NFC标签被移除的情况。以下是一个示例,它在NFC标签被检测到时会显示一个活动,并在NFC标签被移除时关闭该活动:
public class MainActivity extends AppCompatActivity {
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.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
handleNfcIntent(getIntent());
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleNfcIntent(intent);
}
private void handleNfcIntent(Intent intent) {
// This is where you handle the NFC tag's data
// For example, you can display the tag's data in a TextView
// Close this activity when the NFC tag is removed
if (intent.getAction().equals(NfcAdapter.ACTION_TAG_LOST)) {
finish();
}
}
}