错误无法启动 activity:java.lang.illegalStateException:只有在恢复 activity 时才能启用前台调度

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

我正在使用 Xamarin 处理 NFC Android。

我的场景是读取nfc标签。我已经实现了以下功能,它使用一个按钮工作。但我希望这样用户不必按扫描按钮来扫描 nfc 标签。

创建时

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 
    }
}

但是,如果我从 OnCreate 中删除按钮委托,并调用 InitNfcScanner(),我会收到错误无法启动 activity:java.lang.illegalStateException:只有当您的 activity 恢复。

我希望用户能够在加载 activity 后仅扫描资产。实现此目标的好的解决方案是什么?

能否在 OnCreate 中添加按钮委托并在 OnResume 中调用 button.PerformClick()。

我现在已经解决了这个问题。

objective 是为了能够在不按下按钮的情况下读取 nfc 标签。 所以我从视图中删除了按钮,并从 OnCreate 中删除了 ScanButton 委托。

当我在 OnResume() 中调用 InitialiseNfcScanner 时,这就是我所需要的,因为 _nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null); 将创建一个 pendingIntent 并查看 Android 指南,ForgroundDispatch 只能从 OnResume() 调用。

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