前言


Capacitor 自定义插件 实现WebView中访问的自定义Android代码


最近在工作中使用Vue+Vant+Capacitor 开发打包移动端应用,因业务需求需与原生的Android进行数据通信,通过webview访问原生Android中的数据,即Android 与 js 互调。

怎么使用Capacitor打包Vue移动端项目,见之前的一篇文章:

Capacitor+Vue+Vant移动端打包总结

下面是亲测实现了基于Capacitor中Android和js互调。

WebView可访问的本机代码

生成需要在WebView中访问的自定义本机代码的最简单方法是为其构建本地Capacitor插件。在这种情况下,构建插件就像构建一个继承自com.getcapacitor.Plugin并使用@NativePlugin()and @PluginMethod()注释的类一样简单。

一、 自定义插件​​CustomNativePlugin​​:

package xxxxxxx;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import com.getcapacitor.JSObject;
import com.getcapacitor.NativePlugin;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;

/**
* Capacitor CustomNativePlugin 自定义插件
* */
@NativePlugin()
public class CustomNativePlugin extends Plugin {

/**
* customCall 获取加密用户信息
*/
@PluginMethod()
public void customCall(PluginCall call) {
//String message = call.getString("value");
String encryptParams = getParams(MainActivity.getContent());
JSObject jsObject = new JSObject();
jsObject.put("encryptParams",encryptParams);
call.success(jsObject);
}

@PluginMethod()
public void customFunction(PluginCall call) {
// More code here...
JSObject jsObject = new JSObject();
try {
//添加
jsObject.put("name", "张三");
// System.out.println(jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
// Log.d("MSG", jsObject.toString());
call.resolve(jsObject);
}

}

二、在Activity中注册插件:

package xxxx;
import android.content.Context;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;

public class MainActivity extends BridgeActivity {
public static Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this.getApplicationContext();
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
add(CustomNativePlugin.class);
}});
}
/**
* @return content
* */
public static Context getContent(){
return context;
}
}

三、在webView代码中使用函数:

import { Plugins } from "@capacitor/core";
const { CustomNativePlugin } = Plugins;

/**
* 接收Android Capacitor 插件传递过来参数
* */
async getLaunchUrl() {
let param = '';
const ret = await CustomNativePlugin.customCall();
param = ret.encryptParams
return param;
}

Capacitor实现WebView中访问的自定义Android代码_vue

代码结构:

Capacitor实现WebView中访问的自定义Android代码_移动开发_02

参考

​Capacitor Custom Native Code​

有关插件API的更多用法,请参阅​​Capacitor Android Plugin Guide​​。