Use Android's WebView control to call local code

Use Android's WebView control to call local code

The reader is required to have a certain programming foundation in the relevant language.


Brief description of environment setup

* Open http://developer.android.com/ and download the Eclipse version integrated with android SDK

* Open http://www.java.com/ and download the latest version of the corresponding JDK. Note that it is JDK, not JRE

After installation, configure the JAVA_HOME path, open Eclipse, create a new Android Application Project, and run it directly.

If successful, an Android emulator will be opened and helloworld will be displayed.

If the above steps are unsuccessful. . . The next step can only be carried out until it succeeds. . .


When I operate, the SDK version of Eclipse is KitKat. Compared to before, setting up an Android development environment is much simpler.


Open the MainActivity.java file in the project.

Copy the following code in, overwrite the original, recompile and run, you can see the effect.


This is a relatively safe method that I just called out. Part of the code is referenced from the Internet. Please study the details of the code by yourself. You are welcome. (Android 2.1 can also pass)

package com.example.appa;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
	private WebView webview = null;  
	   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //setContentView(R.layout.activity_main);//可要可不要
        initWebWiew();
    }
    
    @JavascriptInterface
    private void initWebWiew() {
    	if( webview == null )
    	{
            //实例化WebView对象  
            webview = new WebView(this);  
            //设置WebView属性,能够执行Javascript脚本  
            webview.getSettings().setJavaScriptEnabled(true);  
            
            //加载第一个页面,页面不能太大
            //loadWebsite();//load外网地址
            loadLocal();//加载本地
            
            
            
            //设置Web视图  
            setContentView(webview);
    	}
    }
    
    private void loadWebsite() {
        //如果页面中链接,如果希望点击链接继续在当前browser中响应,而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
    	webview.setWebViewClient(
    			new WebViewClient(){       
                            public boolean shouldOverrideUrlLoading(WebView view, String url) {       
                                view.loadUrl(url);       
                                return true;       
                            }       
                }
    	);
    	
    	webview.loadUrl("http://www.baidu.com/");
    }
    
    private Handler mHandler = new Handler(); 
    
    @JavascriptInterface
    private void loadLocal() {
    	/*
    	 *这是老版本的写法
    	Object interfaceObject = new Object() {
    		public void onClickAndroid() {
    			mHandler.post(
    					new Runnable() {
    						public void run() {
    							webview.loadUrl("javascript:wave()");
    							
    						}
    					}
    			);
    		}
    	};
    	webview.addJavascriptInterface(interfaceObject,  "androidCallback");
    	*/
    	
    	//android 4.2, JDK1.7后新版本写法
    	webview.addJavascriptInterface(new JsObject(),  "androidCallback"); 
    	
    	//这个 onClickAndroid() 和 androidCallback 的命名,就是对应HTML里面的window.androidCallback.onClickAndroid
    	
    	webview.loadData(tp, "text/html", "utf-8");
    	
    }
    
    private class JsObject {
    	private String param;
    	
        @JavascriptInterface
		public void onClickAndroid(String p) {
        	param = p;
			mHandler.post(
					new Runnable() {
						public void run() {
							Log.d("dbg", "receive param:" + param);
							String s = param + " " + String.valueOf( Math.round( Math.random()*100 ) );
							
							/*
							try {
								s = URLEncoder.encode(s, "utf-8");
							} catch (Exception e) {
								s = "Error";
							}
							*/
							//webview.loadData(s, "text/html", "utf-8");
							webview.loadUrl("javascript:responseFromAndroid('" + s + "')");   
						}
					}
			);
		}
     }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        

        return true;
    }
    
    //如果不做任何处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身,如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {       
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {       
        	webview.goBack();       
                   return true;       
        }       
        return super.onKeyDown(keyCode, event);       
    }     
    
    private static final String tp = 
    		"<font color='#FF00FF'><h1>Test</h1></font>" +
    				"name:<input type='text' id='txtName'/><br>" + 
    				"age:<input type='text' id='txtAge'/><br>" + 
    				"message:<input type='text' id='txtResult' value=''/><br>" + 
    				"<input type='button' id='btnGo' value='go' onClick='onClickA()'/>" + 
    				"<script>" + 
    				"function onClickA() {" + 
    				"  var name = document.getElementById('txtName').value;" + 
    				"  var age = document.getElementById('txtAge').value;" + 
    				"  var s = name + ',' + age;" + 
    				"  window.androidCallback.onClickAndroid(s);" + 
    				"}" +
    				"function responseFromAndroid(s) { " +
    				"document.getElementById('txtResult').value = s;" +
    				"}" +
    				"</script>";    

    
}





Guess you like

Origin blog.csdn.net/RoadToTheExpert/article/details/19199011
Recommended