美文网首页
Android 使用AgentWeb加载h5页面,并互调方法

Android 使用AgentWeb加载h5页面,并互调方法

作者: 因为我的心 | 来源:发表于2024-08-05 11:33 被阅读0次

1、前言

1、官方网站:
2、AgentWeb的使用:

2、build.gradle(Moudle.app)androidx的引用

implementation 'com.just.agentweb:agentweb-androidx:4.1.4'

3、如果项目中h5需要选择图片或者是下载需要添加一下依赖

implementation 'com.just.agentweb:filechooser:4.1.4'// (可选)
implementation 'com.download.library:Downloader:4.1.4'// (可选)

4、如果添加选择图片或下载报错,需要添加一下配置build.gradle(Project:项目名称)

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

5、布局的实现

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    //标题
    <include
        layout="@layout/activity_left_title_text_view"/>

    <LinearLayout
        android:id="@+id/view"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

6、kotlin实现案例

import android.net.http.SslError
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.SslErrorHandler
import android.webkit.WebView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import kotlinx.android.synthetic.main.activity_left_title_text_view.*
import kotlinx.android.synthetic.main.activity_my_web_view.*
import org.jetbrains.anko.toast

/** 
 *@Created by wrs on 2020/9/25,11:43
 *@Description: h5页面加载
 */
class MyWebActivity : BaseActivity(),View.OnClickListener,JsInterfaceListener {

    var mAgentWeb:AgentWeb? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_web_view)
        initView()
        initData()
        initListener()
    }

    override fun initView() {
        tvTitle.text = ""
    }

    private val webChromeClient = object : WebChromeClient(){

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            tvTitle.text = title
        }

    }

    private fun getWebViewClient(): com.just.agentweb.WebViewClient {
        return object : com.just.agentweb.WebViewClient() {
            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler,
                error: SslError?
            ) {
                handler.proceed()
            }
        }
    }


    override fun initData() {
        //访问h5的路径
        val pathUrl = intent.getStringExtra(MyParms.PARAMS)

        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(view, ViewGroup.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setWebChromeClient(webChromeClient)
            .setWebViewClient(getWebViewClient())
            .createAgentWeb()
            .ready()
            .go(pathUrl)
        val webSetting = mAgentWeb?.webCreator?.webView?.settings
        webSetting?.javaScriptEnabled = true
        //此处为agentweb声明js方法
        mAgentWeb?.jsInterfaceHolder?.addJavaObject("android",AndroidInterface(this))
    }

    override fun initListener() {
        ivBack.setOnClickListener(this)
    }

    override fun jsPullUpMethod(method: String, parmas: String) {
        when(method){
            "toMain" ->{//js调用android的方法
                toast("js调用android的方法")
            }
            "toPay" ->{//js调用android的方法
                toast("js调用android的方法")
            }
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.ivBack ->{//返回
                if (mAgentWeb?.back() == true){//返回上一层
                }else{//关闭当前webview界面
                    finish()
                }
            }
        }
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb?.let { it.handleKeyEvent(keyCode, event) } == true) {
            true
        } else super.onKeyDown(keyCode, event)
    }


}

7、AndroidInterface类

import android.webkit.JavascriptInterface;

/**
 *  
 *
 * @Created by wrs on 2020/10/16,13:57
 * @Description: js条用android的方法
 */
public class AndroidInterface extends Object {

    private JsInterfaceListener jsInterface;

    public AndroidInterface(JsInterfaceListener jsInterface) {
        this.jsInterface = jsInterface;
    }

    @JavascriptInterface
    public void jsCallMethod(String method,String params){
        jsInterface.jsPullUpMethod(method,params);
    }

}

8、js调android的监听方法

/** 
 *@Created by wrs on 2020/10/16,14:00
 *@Description: js调用android的方法配合AndroidInterface
 */
interface JsInterfaceListener {

    fun jsPullUpMethod(method:String,params:String)

}

9、js调用android方法的实例

//toMain()是android端定义的方法 不传参数
window.android.toMain();

//toPay("支付参数")是android端定义的方法 传参数
window.android.toPay("支付参数");

window.android.toMain();记得 android区分大小写

10、android调用js方法的实例

//androidpay()h5里的方法 不传参数
mAgentWeb.getJsAccessEntrace().quickCallJs("androidpay");

//androidpay()h5里的方法  传参数
mAgentWeb.getJsAccessEntrace().quickCallJs("androidShare","分享的数据");

mAgentWeb.getJsAccessEntrace().quickCallJs("androidShare","参数1","参数2","参数3");

11、vue.js里面的方法必须这样写

<script >
    export default{
        data(){
            return{
            }
        },
        onLoad() {
        },
        mounted() {
            //这里必须要挂载
            window.androidpay= this.androidpay
            window.androidShare= this.androidShare
        },
        methods:{
            androidpay(){
                console.log("调用到了androidpay");
            },
            androidShare(data){
                console.log("调用到了androidShare");
            },
        }
    }
    
    
</script>

12、agentweb加载其它h5界面

runOnUiThread {
    mAgentWeb?.webCreator?.webView?.loadUrl("url地址")
}

13、agentweb刷新

mAgentWeb?.webCreator?.webView?.reload()

14、如果前段那边需要调试debug可以配置一下设置

AgentWebConfig.debug();

15、清空历史记录

AgentWebConfig.clearDiskCache(this.getContext());

16、AgentWeb加载html的url

//val path = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title></title></head><body><script type='text/javascript'>location.href='https://qr.alipay.com/bax099397hu87eazmpiv8004';</script></body></html>"
 mAgentWeb?.webCreator?.webView?.loadDataWithBaseURL(null,path,"text/html","utf-8",null)

参考:https://www.jianshu.com/p/74c2a330573e

相关文章

网友评论

      本文标题:Android 使用AgentWeb加载h5页面,并互调方法

      本文链接:https://www.haomeiwen.com/subject/fiyxkjtx.html