How JS calls Android native methods

1. Introducing JSBridge

JSBridge mainly provides JavaScript with an interface to call Native functions, so that the front-end part in hybrid development can easily use Native functions (such as: address book, Bluetooth).
Moreover, the function of JSBridge is not as simple and broad as calling Native functions. In fact, JSBridge, just like the Bridge in its name, is a bridge between Native and non-Native. Its core is to build a channel for message communication between Native and non-Native, and this communication channel is bidirectional.

2. JS calls Android native methods

1. Add Javascript interface: assign the interface of related methods of Android to a special js object, and then assign it to the window object, such as PosObj in the following code block project
insert image description here

private void initJs() {
    
    //增加Javascript的接口
        webView.addJavascriptInterface(new MyJSI(this), "PosObj");
    }

2. The method of creating a total js call must be annotated with @JavascriptInterface
insert image description here

@JavascriptInterface
    public String invokeFun(String funName, String json) {
    
    
}
//通用
@JavascriptInterface 
    public void close() {
    
    
 //js调用完以后的逻辑 
 
 }

3. Example: encapsulating the method of obtaining the version number
insert image description here

public String getVersionName(Context context) {
    
    
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageInfo packInfo = null;
        String version = "";
        try {
    
    
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
    
    
            e.printStackTrace();
        }
        return version;
    }

4. js calls the Android method ()//put the handleAndroid method where it needs to be called
insert image description here

    function handleAndroid(){
    
    
            // 由于对象映射,所以调用PosObj对象等于调用Android映射的对象
            //getVersionName是Android的方法
            window.PosObj.invokeFun('getVersionName', '')
        }

Guess you like

Origin blog.csdn.net/wangbaobao512/article/details/127219629