安卓嵌入h5页面方法笔记

在这里插入图片描述

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

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://m.atguigu.com/");
        

    }
    //监听系统返回键,如果有上个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);
                                }
                            });
                        }
                    }
                });

        }
    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Uniapp是一款基于Vue.js框架的跨平台开发工具,支持在一套代码中开发出运行于各大平台的应用程序。当我们需要在Uniapp应用程序中嵌入h5页面时,可以通过使用uniWebView组件来实现。uniWebView是Uniapp官方提供的一个支持在小程序、APP中加载H5页面、原生组件的组件。下面简单介绍一下uniWebView组件的使用。 首先,在需要使用webview页面中导入uniWebView组件: ``` <template> <view class="uni-page"> <uni-web-view :src="url"></uni-web-view> </view> </template> <script> import uniWebView from '@/components/uni-web-view/uni-web-view.vue'; export default { components: { uniWebView }, data() { return { url: 'https://www.baidu.com' // 设置要加载的H5地址 } } } </script> ``` 在页面中添加uni-web-view标签,并通过src属性指定需要加载的H5页面的地址。当然,我们还可以通过设置其他属性来控制webview的行为,比如设置webview的高度、宽度、背景颜色、是否启用缩放等。 需要注意的是,在使用uniWebView组件时,需要在manifest.json中配置webview权限,否则会导致无法加载H5页面。在manifest.json文件中,我们需要添加以下代码: ``` "app-plus": { "useWebview": true, // 允许使用webview组件 "webview": { "popGesture": "close", "subNViews": true, // 开启uni-subNVue "bounce": "none", "plusrequire": "none", "uniNView": { "defaultFontSize": 16 }, "permission": { "webview": { "default": { "state": 1, // 允许加载H5页面 "des": "WebView 权限" } } }, } } ``` 通过以上配置,我们就可以在Uniapp应用程序中顺利地嵌入H5页面,并且能够自由地控制webview的行为。但需要注意的是,由于uniWebView组件比较占用资源,因此还需要充分优化应用程序性能,避免出现卡顿等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值