安卓嵌入h5页面方法笔记

安卓嵌入h5页面方法笔记_第1张图片


<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>

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);
                                }
                            });
                        }
                    }
                });

        }
    }

}

安卓嵌入h5页面方法笔记_第2张图片

你可能感兴趣的:(安卓,android,笔记)