Xamarin.Android 入门之:xamarin使用webserver和html交互

一、引言

如今,Android+html5开发已经成为最流行的开发模式。

Android 中可以通过webview来实现和js的交互,在程序中调用js代码,只需要将webview控件的支持js的属性设置为true

Android(Java)与JavaScript(HTML)交互有四种情况:

1) Android(Java)调用HTML中js代码

2) Android(Java)调用HTML中js代码(带参数)

3) HTML中js调用Android(Java)代码

4) HTML中js调用Android(Java)代码(带参数)

二、准备工作 

1.添加一个Android项目,在Assets中添加一个名为Test的html文件

2.添加以下html代码到Test.html

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
    <script type="text/javascript">
function javacalljs(){
     document.getElementById("content").innerHTML +=
         "<br>java调用了js函数";
}

function javacalljswithargs(arg){
     document.getElementById("content").innerHTML +=
         ("<br>"+arg);
}

    </script>
</head>
<body>
    this is my html <br />
    <a onClick="window.Test.startFunction()">点击调用java代码</a><br />
    <a onClick="window.Test.startFunction('hello world')">点击调用java代码并传递参数</a>
    <br />
    <div id="content">内容显示</div>
</body>
</html>
View Code

3.删除layout文件夹下的main.axml文件的原油控件,添加以下控件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="9" />
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/msg"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="text" />
    </ScrollView>
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="java调用js函数" />
</LinearLayout>
View Code

三、代码

1.在MainActivity.cs中删除原来的代码,替换以下代码

 [Activity(Label = "WebService", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity, Button.IOnClickListener//继承按钮的点击接口
    {
        /// <summary>
        /// 定义控件
        /// </summary>
        public WebView webview;
        public TextView msgtext;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            //找到控件
            webview = FindViewById<WebView>(Resource.Id.webview);
            msgtext = FindViewById<TextView>(Resource.Id.msg);

            //找到按钮并坚挺点击事件
            Button button = FindViewById<Button>(Resource.Id.button);
            button.SetOnClickListener(this);

            webview.Settings.JavaScriptEnabled = true;//设置webserver支持js
            webview.AddJavascriptInterface(this, "Test");//添加js接口
            webview.LoadUrl("file:///android_asset/Test.html");//加载html的地址
           //webview.LoadUrl(this.GetString(Resource.String.Url));//如果我们的html文件实在服务器端则这边可以填服务器端的地址例如127.0.0.1:91/Test.html
        }
        public void OnClick(View v)
        {
            // 无参数调用  
            webview.LoadUrl("javascript:javacalljs()");
            // 传递参数调用  
            webview.LoadUrl("javascript:javacalljswithargs(" + "'hello world'" + ")");
        }

        [Export("startFunction")]
        public void startFunction()
        {
            RunOnUiThread(new Runnable(() =>
            {
                msgtext.Text = msgtext.Text + "
js调用了java函数";
            }));
        }
        /// <summary>
        /// 当用户调用了这个方法会传递过来一个参数,我们可以获取出来然后用Android的toast显示
        /// </summary>
        /// <param name="str"></param>
        [Export("startFunction")]
        public void startFunction(string str)
        {
            Toast.MakeText(this, str, ToastLength.Short).Show();
            RunOnUiThread(new Runnable(() =>
            {
                msgtext.Text = msgtext.Text + "
js调用了js函数"+str;
            }));
        }
    }
View Code

2.最后在虚拟机上运行,当我们点击“点击调用java代码”的时候在我们程序中多了一行文字,当我们点击“点击调用java代码并传递参数”,程序除了添加了一行文字之外还跳出了提示。当我们点击java调用js函数在我们html页面山会把我们传递的参数显示出来。好了简单的Android和html的交互就是这样。配上项目地址https://github.com/huguodong/WebService

原文地址:https://www.cnblogs.com/huguodong/p/5843182.html