Xamarin Android Webview中JS調用App中的C#方法


參考鏈接:https://github.com/xamarin/recipes/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript

一、MainActivity中

//這個方法用於讓H5調用android方法
web_view.AddJavascriptInterface(new JSXamarin(this), "JSXamarin");

二、定義一個接口類:

    public class JSXamarin : Java.Lang.Object
    {
        Context context;

        public JSXamarin(Context context)
        {
            this.context = context;
        }

        public JSXamarin(IntPtr handle, JniHandleOwnership transfer)
            : base(handle, transfer)
        {
        }

        [Export("ShowToast")]
        [JavascriptInterface]
        public void ShowToast(Java.Lang.String message)
        {
            Toast.MakeText(context, "Hello from C#"+message, ToastLength.Short).Show();
        }

    }

  

        [Export("ShowToast")]
        [JavascriptInterface]
16版本以上這兩個屬性不能少,需要引用一個Mono.Android.Export.dll

 

三、Web客戶端調用:

        function PrintSMDLab() {
            JSXamarin.ShowToast(‘測試文字');
        }

  

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM