三步搞定:Vue.js调用Android原生方法
16lz
2021-01-23
第一步: Android对Js的接口,新建AndroidInterfaceForJs.js
import android.content.Context;import android.os.Build;import android.os.Handler;import android.os.Looper;import android.support.annotation.RequiresApi;import android.util.Log;import android.webkit.JavascriptInterface;import android.webkit.ValueCallback;import android.widget.Toast;import com.just.agentweb.AgentWeb;import com.yidumedical.ui.activity.PAWebActivity;/** * Created by shiby on 2018/1/24. */public class AndroidInterfaceForJS { private Handler deliver = new Handler(Looper.getMainLooper()); private AgentWeb agent; private Context context; public AndroidInterfaceForJS(AgentWeb agent, Context context) { this.agent = agent; this.context = context; } @JavascriptInterface public void callAndroid(final String msg) { deliver.post(new Runnable() { @Override public void run() { Log.i("Info", "main Thread:" + Thread.currentThread()); Toast.makeText(context.getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show(); } }); Log.i("Info", "Thread:" + Thread.currentThread()); }}
第二步: 给WebView中的window注入对象(例子使用的是AgentWeb)
private void init(){ mAgentWeb = AgentWeb .with(this)//传入Activity or Fragment .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ,如果父控件为 RelativeLayout , 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。 .useDefaultIndicator()// 使用默认进度条 .defaultProgressBarColor() // 使用默认进度条颜色 .createAgentWeb()// .ready() .go(baseURL); //注入对象 mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterfaceForJS(mAgentWeb,this.getApplicationContext())); AgentWebSettings agentWebSettings = mAgentWeb.getAgentWebSettings(); agentWebSettings.getWebSettings().setDomStorageEnabled(true);}注入对象:
//注入对象 mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterfaceForJS(mAgentWeb,this.getApplicationContext()));
第三步:在Vue里面直接调用方法(简单粗暴法):
window.android.callAndroid('调用成功,耶!!!')考虑到项目的可维护性,一般不这样写。
优雅法:
新建app.js
constandroid =window.androidexport {android }
将 window.android存在该模块,方便更改
然后在需要的.js或者.vue文件中,导入app模块,然后使用
import {android}from'../app'try {android.callAndroid('调用成功,耶!!!')}catch (e) {console.log('出现错误, 如果在非android环境下访问, 出现该警告是正常的.')}更多相关文章
- Android高手进阶教程(十七)之---Android中Intent传递对象的两种
- Android中将资源文件转为Bitmap对象
- Android UI 之时间与日期控件
- 面向UDP的Android——PC双向通信(三):在Android客户端和PC服务器端
- Android调用WebService系列之KSoap2对象解析
- android常用UI控件的使用例子
- Android控件常用属性
- android中控件的遮盖问题
- Android 模拟器创建参数说明