1. 程式人生 > >Xamarin如何使用終端裝置的NFC功能傳遞卡號等資訊給Web頁面(Android)

Xamarin如何使用終端裝置的NFC功能傳遞卡號等資訊給Web頁面(Android)

一、前提條件,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); } }
NFC處理類

三、與之相關的主活動方法

        public void SetNFCData(string nfcid)
        {
            //EvaluateJavascript不會重新整理頁面
            //呼叫H5頁面的函式,賦值給文字框或變數都可以
            string script = "javascript:SetNFCID('"+ nfcid + "');";
            web_view.EvaluateJavascript(script, null);
        }
    

四、由此,就可以實現在終端上感應源,獲取源的資訊到Web頁面之中了。