Android引入J2V8框架解决 java与js通信

优点:可以实现java和js之间的调用(适用于只有java和js文件之间的通讯) 其他有webview的没必要使用这种方法
缺点:apk增加将近7MB: 所用到的资源必须手动释放
1:在build.gradle中添加依赖

dependencies {
    compile 'com.eclipsesource.j2v8:j2v8:4.5.0@aar'
}

2:必须创建运行环境,用完必须释放

V8 runtime = V8.createV8Runtime();//创建 可放在onCreate()当中
//操作
runtime.release();//释放  可放在onDestroy()当中

3:创建之后,加载写好的js文件,里面包含java可能调用的js方法和一些数据
2:java里面加载js文件的异步任务类:

package com.carnoc.news.j2v8;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;

import com.amap.api.services.proguard.bf;
import com.carnoc.news.model.HotColumnInfoModel;
import com.carnoc.news.task.AsyncTaskBackListener;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Desc:
 * Created by qyn on 2018/4/9.
 */

public class J2V8ReadJavaScript extends AsyncTask
{
    private AsyncTaskBackListener listener;

    private String fileName;
    private Activity activity;
    public J2V8ReadJavaScript(Activity activity, AsyncTaskBackListener listener, String fileName)
    {
        this.listener = listener;
        this.fileName = fileName;
        this.activity = activity;

    }
    public J2V8ReadJavaScript()
    {
        super();
    }
    public static String getFileContent(String fileName, Context context)
    {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try
        {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null)
            {
                stringBuilder.append(line).append("\r\n");//为了保证js的严格“行”属性,这里主动追加\r\n
            }
            bf.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }
    @Override
    protected String doInBackground(String... strparams)
    {

        String jsString = getFileContent(this.fileName, this.activity);

        return jsString;
    }
    @Override
    protected void onPostExecute(String result)
    {
        if (listener != null)
        {
            listener.onAsyncTaskCallBack(result);
        }
    }
}

3:java里面初始化数据

        J2V8ReadJavaScript readJavaScript = new J2V8ReadJavaScript(mActivity, new AsyncTaskBackListener()
        {
            @Override
            public void onAsyncTaskCallBack(String s)
            {

                if (v8 != null && !v8.isReleased())
                {
                    registerJavaMethod();
                    v8.executeScript(s);
                    ///初始化JS数据
                    V8Array defaultDatas;
                    defaultDatas = new V8Array(v8);//1:id,2:image,3:color,4:follow,5:platform
                    defaultDatas.push(2);//2:android
                    v8.executeVoidFunction("initViewModel", defaultDatas);
                    defaultDatas.release();
                    initData();
                }
            }
        }, "JsonHandleJS/quick_news.js");

        readJavaScript.execute();

4:java调用js函数处理,这里因为常用的就几种,所以写了一个公共的工具:

package com.carnoc.news.util;

import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;

/**
 * Desc:
 * Created by qyn on 2018/4/17.
 */

public class J2V8Util
{
    /**
     *
     * @param v8
     * @param name js函数名
     * @return  返回字符串
     */
    public static String v8String(V8 v8, String name)
    {
        String result = "";
        if (v8 != null&&!v8.isReleased())
            result = v8.executeStringFunction(name, null);
        return result;
    }

    /**
     *
     * @param v8
     * @param name js函数名
     * @param position  传入参数
     * @return  返回字符串
     */
    public static String v8String(V8 v8, String name, int position)
    {
        String result = "";
        if (v8 != null&&!v8.isReleased())
        {
            V8Array array = new V8Array(v8);
            array.push(position);
            result = v8.executeStringFunction(name, array);
            array.release();
        }

        return result;
    }

    /**
     * 
     * @param v8
     * @param name  js函数名
     * @return  boolean类型
     */
    public static boolean v8Boolean(V8 v8, String name)
    {
        boolean result = false;
        if (v8 != null&&!v8.isReleased())
            result = v8.executeBooleanFunction(name, null);
        return result;
    }

    public static boolean v8Boolean(V8 v8, String name, int position)
    {
        boolean result = false;
        if (v8 != null&&!v8.isReleased())
        {
            V8Array array = new V8Array(v8);
            array.push(position);
            result = v8.executeBooleanFunction(name, array);
            array.release();
        }

        return result;
    }

    public static int v8Int(V8 v8, String name, int position)
    {
        int result = 0;
        if (v8 != null&&!v8.isReleased())
        {
            V8Array array = new V8Array(v8);
            array.push(position);
            result = v8.executeIntegerFunction(name, array);
            array.release();
        }

        return result;
    }

    public static int v8Int(V8 v8, String name)
    {
        int result = 0;
        try
        {
            if (v8 != null&&!v8.isReleased())
                result = v8.executeIntegerFunction(name, null);
        }
        catch (Exception e)
        {

        }

        return result;
    }

    public static void v8Void(V8 v8, String name, int position)
    {
        if (v8 != null&&!v8.isReleased())
        {
            V8Array array = new V8Array(v8);
            array.push(position);
            v8.executeVoidFunction(name, array);
            array.release();
        }

        return;
    }

    public static void v8Void(V8 v8, String name)
    {
        if (v8 != null&&!v8.isReleased())
            v8.executeVoidFunction(name, null);
        return;
    }
}

5:js调用java 这个需要在调用之前 在v8里面注册方法名 例如:

 if (v8 != null && !v8.isReleased())
 {
//参数1:context  参数2:java方法名,参数三:js里面写的方法名  参数4:方法的参数类型 个数
            v8.registerJavaMethod(mContext, "getTitleHeightFromNative", "getTitleHeightFromNative", new Class[]{String.class})   
  }


public void getTitleHeightFromNative(String str){

}

你可能感兴趣的:(Android引入J2V8框架解决 java与js通信)