在onPause()方法中关闭前一个Activity的NFC侦听器,以确保不会在后续活动中触发不必要的NFC扫描。在新的Activity中,您可以根据需要打开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);
if (nfcAdapter == null) {
// NFC is not supported by the device
return;
}
// Enable NFC scanning for the activity
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter[] intentFilters = new IntentFilter[] {};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
@Override
protected void onPause() {
super.onPause();
// Disable NFC scanning for the activity
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onResume() {
super.onResume();
// Enable NFC scanning for the activity
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter[] intentFilters = new IntentFilter[] {};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Handle new NFC tag scanned
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// Process tag data...
}
}