三步搞定:Vue.js调用Android原生操作

第一步: 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

const android = window.android

export { android }

将 window.android存在该模块,方便更改

然后在需要的.js或者.vue文件中,导入app模块,然后使用

import {android} from '../app'
try {
android.callAndroid('调用成功,耶!!!')
} catch (e) {
console.log('出现错误, 如果在非android环境下访问, 出现该警告是正常的.')
}

补充知识:vue与原生安卓相互调用

最近公司有做直播类的项目,由于直播框架限制,限制所用的技术是vue搭建的H5页面嵌入到原生安卓中。由于之前没有过类似的混合开发经验,所以今天写篇博客加深下印象。

vue.js调用安卓方法

先将vue项目放到一个内网地址或者外网地址中,然后安卓端通过“webView.loadUrl()”将vue项目引入。安卓端将要调用的方法名暴露在window对象中,由vue直接在methods中调用并携带参数。

 methods:{
  goPublish(){
   //将vue项目引入至安卓代码中,安卓方法暴露在window中,vue中可以直接用window去调取方法。
   window.android.callAndroidMethod('1','2')
  }
 }

安卓调用vue.js中的方法

同样的vue也需要把方法添加到window中去,再由安卓端去调取方法。

 created(){
 //需要在created钩子中将方法添加到window对象中
  window.setFun = this.setFun;
 },
 methods:{
  setFun(arg) {
   //arg: 原生调用Vue时传值(arg)给Vue
   console.log("获取到android的传参:" + arg);
  },
 }

以上就是vue与安卓端项目调用的大致方法,有用词不当的地方望海涵且不吝指正。希望能给大家一个参考,也希望大家多多支持来客网。