Android: 간단 한 webView 와 js 의 상호작용

3073 단어
간단 한 대화 하나 로 저 는 효과 도 를 보 내지 않 겠 습 니 다.
Html


    
    Carson
    
         function callAndroid(){
        //       ,    test      Android     
            test.hello("js   android  hello  ");
         }
         function callJS(){
        //       ,    test      Android     
            alert("Android   JS callJS  ");
         }
      


//       callAndroid  

Activity

WebView mWebView;
Button button;

@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView =(WebView) findViewById(R.id.webview);
    WebSettings webSettings = mWebView.getSettings();
    //    Js     
    webSettings.setJavaScriptEnabled(true);
    //     JS  
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    mWebView.addJavascriptInterface(new AndroidtoJs(), "test");//AndroidtoJS      js test  
    //    JS  
    //      :file:///android_asset/   .html
    mWebView.loadUrl("file:///android_asset/javascript.html");
    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            //   Handler    
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    //      JS       
                    //   javascript callJS()  
                    mWebView.loadUrl("javascript:callJS()");
                }
            });
        }
    });
    //              ,      js   
    // webview    ,         webviewChromClient    
    //     WebChromeClient    JavaScript    
    //    js  Alert()  
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
            b.setTitle("Alert");
            b.setMessage(message);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            b.setCancelable(false);
            b.create().show();
            return true;
        }
    });
}

Js 대화 형 Android 클래스
package com.wd.androidjs;

import android.util.Log;
import android.webkit.JavascriptInterface;

class AndroidtoJs extends Object{
    //   JS       
    //  JS         @JavascriptInterface  
    @JavascriptInterface
    public void hello(String msg) {
        Log.e("my",""+msg);
    }
}

좋은 웹페이지 즐겨찾기