安卓嵌入h5页面方法笔记

html 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TestApplication"
        android:usesCleartextTraffic="true"
        tools:targetApi="31">
        <activity
            android:name=".Order"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NotiyFactionActivity" />
        <activity android:name=".TestActiv" />
    </application>

</manifest>
java 复制代码
package com.example.testapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    private NotificationManager manager;
    private Notification notification;
    private WebView webview;

    Context ctx = this;
    @SuppressLint({"MissingInflatedId", "JavascriptInterface"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        //安卓嵌入h5

//        webview = (WebView) findViewById(R.id.id_wv);
        webview=new WebView(this);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setAllowFileAccessFromFileURLs(true);
        webview.getSettings().setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setLoadsImagesAutomatically(true);
        //不调用外部浏览器,一直在APP内运行网页
        webview.setWebViewClient(new WebViewClient() );
        //响应webview 加载H5页面中的alert函数,否则alert显示不出来
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(ctx);
                b.setTitle("title");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.create().show();
                return true;
            }
        });
        //添加JavaScript接口,js调用Java要用
        webview.addJavascriptInterface(new JavaAndJsInterface(),"AndroidDemo");
        webview.loadUrl("http://qc.5gxt.top/admin/login/index.html");
        setContentView(webview);

    }
    //监听系统返回键,如果有上个html则返回,否则退出这个页面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    public class JavaAndJsInterface{
        //js调用Java方法
        @JavascriptInterface
        public void javaFn(String arg){
            Toast.makeText(MainActivity.this, "java被js调用了,"+arg, Toast.LENGTH_SHORT).show();
            this.javaDjs();
        }
        //java调用js方法

        //js调用安卓,打电话
        @JavascriptInterface
        public void callPhone(String num){
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+num)));
        }
        public void javaDjs(){
            //java调用浏览器的js函数
            // 通过Handler发送消息
            webview.post(new Runnable() {
                @Override
                public void run() {

                        // 注意调用的JS方法名要对应上
                        // 调用javascript的callJS()方法
                        final int version = Build.VERSION.SDK_INT;//获取系统版本
                        //我们需要判断当前系统版本。为了尽可能减少错误我们使用了两种方式来实现调用JS方法。
                        if (version < 18) {
                            //无法获取js函数的返回值
                            webview.loadUrl("javascript:alertFn('Java调用了js,我是参数1')");
                        } else {

                            webview.evaluateJavascript("javascript:alertFn('Java调用了js,我是参数2')", new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String value) {
                                    //此处为 js 返回的结果
                                    Log.e("leo", value);
                                }
                            });
                        }
                    }
                });

        }
    }

}
相关推荐
雍凉明月夜13 分钟前
c++ 精学笔记记录Ⅰ
开发语言·c++·笔记
QING61842 分钟前
Jetpack Compose Brush API 简单使用实战 —— 新手指南
android·kotlin·android jetpack
Swizard1 小时前
别让 AI 假装在工作:Android "Vibe Coding" 的生存指南
android·java·vibe coding
电饭叔1 小时前
《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之一(Luhn算法解释)
android·java·python
自不量力的A同学2 小时前
FreeFileSync 14.6 发布
笔记
可可苏饼干2 小时前
ELK(Elastic Stack)日志采集与分析
linux·运维·笔记·elk
QING6182 小时前
Jetpack Compose Brush API 详解 —— 新手指南
android·kotlin·android jetpack
Huanzhi_Lin2 小时前
安卓连接夜神模拟器命令及原理
android
AllBlue2 小时前
unity调用安卓方法
android·unity·游戏引擎
s1ckrain3 小时前
数字逻辑笔记—组合逻辑电路
笔记·fpga开发·嵌入式