我正在使用Xamarin Android使用NFC。
我的方案是阅读nfc标签。我已经实现了以下,使用按钮工作。但我希望这样,用户无需按扫描按钮即可扫描nfc标签。
的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
}
}
但是,如果我从OnCreate中删除按钮委托,并调用InitNfcScanner(),则会收到错误无法启动活动:java.lang.illegalStateException:只有在恢复活动时才能启用前台调度。
我希望用户能够在加载活动后立即扫描资产。实现这一目标的好方法是什么?
答案 0 :(得分:0)
是否可以在OnCreate中添加按钮委托,并在OnResume中调用button.PerformClick()。
答案 1 :(得分:-1)
我现在已经解决了这个问题。
目标是能够在不按下按钮的情况下读取nfc标签。 所以我从视图中删除了按钮,然后从OnCreate中删除了ScanButton代理。
当我在OnResume()中调用InitialiseNfcScanner时,这就是我所需要的,因为_nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null);
为了创建一个pendingIntent并查看Android准则,只能从OnResume()调用ForgroundDispatch。
参见http://developer.android.com/reference/android/nfc/NfcAdapter.html enableForegroundDispatch