Search code examples
c#androidxamarinxamarin.androidxamarin-studio

Error Unable to start activity: java.lang.illegalStateException: Foreground dispatch can only be enabled when your activity is resumed


I am working with NFC using Xamarin Android.

My scenario is to read nfc tag. I have implemented the following, which works using a button. But I would like it so the user doesn't have to press Scan button to scan nfc tag.

OnCreate

scanButton.Click += (object sender, EventArfs e) =>{
    var view = (View)sender;
    if(view == Resource.Id.scan){
        var mesgEl = FindViewById<TextView>(Resource.Id.msg);
        msgEl.Text = "Ready to Scan. Touch and hold the tag against the phone.";
        InitNfcScanner();
    }
}

InitNfcScanner

private void InitialiseNfcScanner(){

// Create an intent filter for when an NFC tag is discovered.  When
// the NFC tag is discovered.
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 {
       // display message here
    });
    alert.Show ();
  } else {
   _nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null);
   }
}

OnNewIntent

protected override void OnNewIntent(Intent intent)
{
// onResume gets called after this to handle the intent
Intent = intent;
}

OnResume()

protected override void OnResume ()
{
    base.OnResume ();

    InitialiseNfcScanner();

    if (NfcAdapter.ActionTagDiscovered == Intent.Action) {
        // do stuff 
    }
}

But if i remove the button delegate from OnCreate, and call InitNfcScanner(), I get the error Unable to start activity: java.lang.illegalStateException: Foreground dispatch can only be enabled when your activity is resumed.

I want the user to be able to just scan the asset, once the activity is loaded. What would be a good solution to achieve this?


Solution

  • I have now resolved this issue.

    The objective was to be able to read nfc tag without pressing Button. So i removed the button from the view, and I removed the ScanButton delegate from OnCreate.

    As I was calling InitialiseNfcScanner inside the OnResume(), this is all i needed, because _nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null); would create a pendingIntent and looking at the Android Guidelines for this, the ForgroundDispatch can only been called from the OnResume().

    See http://developer.android.com/reference/android/nfc/NfcAdapter.html enableForegroundDispatch