Home  >  Article  >  Web Front-end  >  Simple interaction between android and js

Simple interaction between android and js

不言
不言Original
2018-04-10 13:39:231590browse

This article introduces the code about the simple interaction between android and js. Now I share it with everyone. Friends in need can refer to it

Permissions:

94d69beb0d03745d3f94a8daa5bc2f77715e355a41f150f13c9dfb3c5419088c


##MainActivity:

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;


/**
 * 注意事项:如何避免WebView内存泄露?
 * 不在xml中定义 Webview ,而是在需要的时候在Activity中创建,并且Context使用 getApplicationgContext()
 * <p>
 * 在 Activity 销毁( WebView )的时候,
 * 先让 WebView 加载null内容,然后移除 WebView,再销毁 WebView,最后置空
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private WebView web;
    private Button but;
    private Button but2;
    private WebSettings settings;
    private Button but3;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        but = findViewById(R.id.but);
        but2 = findViewById(R.id.but2);
        but3 = findViewById(R.id.but3);
        web = findViewById(R.id.web);




        but.setOnClickListener(this);
        but2.setOnClickListener(this);
        but3.setOnClickListener(this);


        //声明WebSettings子类
        settings = web.getSettings();
        //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
        settings.setJavaScriptEnabled(true);
        //设置自适应屏幕,两者合用
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        // 设置与Js交互的权限
        settings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 先载入JS代码

        // 复写shouldOverrideUrlLoading()方法,使得打开网页时不调用系统浏览器, 而是在本WebView中显示
        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });




        // 由于设置了弹窗检验调用结果,所以需要支持js对话框
        // webview只是载体,内容的渲染需要使用webviewChromClient类去实现
        // 通过设置WebChromeClient对象处理JavaScript的对话框
        //设置响应js 的Alert()函数(回调方法)
        web.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("Alter");
                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;
            }
        });










    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //获取本地html文件
            case R.id.but:
                web.loadUrl("file:///android_asset/index.html");
                break;
            //与js交互
            case R.id.but2:


                web.post(new Runnable() {
                        @Override
                        public void run() {
                            // 格式规定为:file:///android_asset/文件名.html
                            web.loadUrl("file:///android_asset/webview.html");
                            web.loadUrl("javascript:callJs()");


                        }
                    });




                break;
            case R.id.but3:
                web.loadUrl("http://www.baidu.com/");


                break;


        }




    }




    //销毁
    @Override
    protected void onDestroy() {
        if (web != null) {
            web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            web.clearHistory();


            ((ViewGroup) web.getParent()).removeView(web);
            web.destroy();
            web = null;
        }


        super.onDestroy();
    }
}


xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.webview_js.MainActivity">


    <Button
        android:id="@+id/but"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点我调用本地html文件" />


    <Button
        android:text="点我调用网站"
        android:id="@+id/but3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <Button
        android:id="@+id/but2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点我与Js交互" />


    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>




</LinearLayout>


html文件(js):
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script>
			
			function callJs(){
				alert("android调用了JS的call方法")
			}
			
		</script>
	</head>
	<body>
		
		
	</body>
</html>

Related recommendations:

Detailed explanation of the steps of interaction between Ajax() and the background

##The use of jsbridge for the interaction between android and js

Ajax PHP data interaction implementation

The above is the detailed content of Simple interaction between android and js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:js control keyframesNext article:js control keyframes