一、前提条件,App必须具有NFC权限。
二、项目中加入监控类NFCCatchActivity.cs
[Activity(Label = "NFCCatch",Theme = "@android:style/Theme.NoDisplay")] [IntentFilter(new[] { "android.nfc.action.TECH_DISCOVERED" })] [MetaData("android.nfc.action.TECH_DISCOVERED", Resource = "@xml/nfc_tech_filter")] public class NFCCatchActivity : Activity { NfcAdapter mNfcAdapter; PendingIntent mPendingIntent; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); mNfcAdapter = NfcAdapter.GetDefaultAdapter(this); if (mNfcAdapter == null) { //textViewNFC.Text = "NFC is not available on this device."; } else { mPendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(NFCCatchActivity)), PendingIntentFlags.UpdateCurrent); OnNewIntent(Intent); } } protected override void OnResume() { base.OnResume(); if (mNfcAdapter != null) mNfcAdapter.EnableForegroundDispatch(this, mPendingIntent, null, null); } protected override void OnPause() { base.OnPause(); if (mNfcAdapter != null) mNfcAdapter.DisableForegroundDispatch(this); } public static string ByteArrayToString(byte[] ba) { string hex = BitConverter.ToString(ba); string rtnStr = ""; string timeN = DateTime.Now.ToString("ssmmHHddMMyyMMyyddHHmmssMMddHHmm"); string tmp1 = ""; string tmp2 = ""; } rtnStr = tmp1 + hex + tmp2; return rtnStr; } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); Intent = intent; Tag tag = (Tag)intent.GetParcelableExtra(NfcAdapter.ExtraTag); string cardID = ByteArrayToString(tag.GetId()); //本活动为后台运行,在获取到IC卡号之后,调用主活动中的方法处理实际业务,如反馈给H5页面。 MainActivity.instance.SetNFCData(cardID); } }
三、与之相关的主活动方法
public void SetNFCData(string nfcid) { //EvaluateJavascript不会刷新页面 //调用H5页面的函数,赋值给文本框或变量都可以 string script = "javascript:SetNFCID('"+ nfcid + "');"; web_view.EvaluateJavascript(script, null); }
四、由此,就可以实现在终端上感应源,获取源的信息到Web页面之中了。