WebView与H5的交互

H5Activity

package com.asker202.myservice;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class H5Activity extends AppCompatActivity implements View.OnClickListener{
private WebView wv;
    private Button btn;
    private String url="file:///android_asset/js.html";//文件放在assets中
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_h5);
        wv= (WebView) findViewById(R.id.wv);
        btn= (Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);
        WebSettings webSettings = wv.getSettings();
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);//设置可响应js
        webSettings.setSupportZoom(false);
        wv.setWebChromeClient(new WebChromeClient());
        wv.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");//注入本地方法
        wv.loadUrl(url);

    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btn)
        {
            wv.loadUrl("javascript:wave()");//调用js方法
        }
    }

    final class DemoJavaScriptInterface {

        DemoJavaScriptInterface() {
        }
        /**
         * @author 孙磊磊
         * create at 2016/3/16 16:50
         * description 4.2及以上版本,需要加 @JavascriptInterface
         */
        @JavascriptInterface
        public void click() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    btn.setText("从网页上调用本地方法");
                    Toast.makeText(H5Activity.this,"从网页上点击了我",Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}
js.html



    http-equiv="Content-Type" content="text/html; charset=UTF-8"/>


    
    
    


id="text">

布局文件也加上吧

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.asker202.myservice.H5Activity">
    



你可能感兴趣的:(Android初级)