I am learning how to use Xamarin with NFC. In the sample I have (https://github.com/xamarin/monodroid-samples/tree/master/NfcSample) it works fine. However, this is a single activity app. My application is a multiple activity app. Also, the same sets the EnableForegroundDispatch on the press of a button. I set it during onResume.
OnNewIntent never gets called. I am new to Xamarin and Android, so this is above my head. I've read some things about SingleTop, but I can't wrap my head around it. Does it have something to do with the activity being reused? If so, how do I fix it? Any help is greatly appreciated. Here is the code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.NFC);
// Get a reference to the default NFC adapter for this device. This adapter is how an Android application will interact with the actual hardware.
_nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
}
protected override void OnNewIntent(Intent intent)
{
if (_inWriteMode)
{
_inWriteMode = false;
var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
if (tag == null)
{
return;
}
// This object is used to get information about the NFC tag as well as perform operations on it.
var ndef = Ndef.Get(tag);
if (ndef != null) {
ndef.Connect ();
//Read Tag - convert from byte array to string
NdefRecord[] recs = ndef.NdefMessage.GetRecords ();
//byte[] type = recs[0].GetType();
byte[] value = recs [0].GetPayload ();
var str = System.Text.Encoding.Default.GetString (value);
Log.Debug ("Tag Value", str);
Toast.MakeText (this, str, ToastLength.Short).Show ();
this.Finish();
}
}
}
protected override void OnResume()
{
base.OnResume ();
EnableWriteMode();
}
protected override void OnPause()
{
base.OnPause();
// App is paused, so no need to keep an eye out for NFC tags.
if (_nfcAdapter != null)
_nfcAdapter.DisableForegroundDispatch(this);
}
/// <summary>
/// Identify to Android that this activity wants to be notified when
/// an NFC tag is discovered.
/// </summary>
private void EnableWriteMode()
{
_inWriteMode = true;
// Create an intent filter for when an NFC tag is discovered. When
// the NFC tag is discovered, Android will u
var tagDetected = new IntentFilter(NfcAdapter.ActionTagDiscovered);
var filters = new[] { tagDetected };
// When an NFC tag is detected, Android will use the PendingIntent to come back to this activity.
// The OnNewIntent method will invoked by Android.
var intent = new Intent(this, GetType()).AddFlags(ActivityFlags.SingleTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
if (_nfcAdapter == null) {
var alert = new AlertDialog.Builder (this).Create ();
alert.SetMessage ("NFC is not supported on this device.");
alert.SetTitle ("NFC Unavailable");
alert.SetButton ("OK", delegate {
//_writeTagButton.Enabled = false;
//_textView.Text = "NFC is not supported on this device.";
});
alert.Show ();
} else
_nfcAdapter.EnableForegroundDispatch(this, pendingIntent, filters, null);
}