Android utilize V8 without WebView

后端 未结 5 858
甜味超标
甜味超标 2020-12-12 13:55

I\'m exercising executing javascript from Java. Rhino works very well for this on desktop, but has to fall back to (slow) interpreted mode on Android (due to dalvik being u

5条回答
  •  爱一瞬间的悲伤
    2020-12-12 14:21

    I found this really nifty open source ECMAScript compliant JS Engine completely written in C called duktape

    Duktape is an embeddable Javascript engine, with a focus on portability and compact footprint.

    You'd still have to go through the ndk-jni business, but it's pretty straight forward. Just include the duktape.c and duktape.h from the distributable source here(If you don't want to go through the build process yourself) into the jni folder, update the Android.mk and all that stuff.

    Here's a sample C snippet to get you started.

    #include "duktape.h"
    
    JNIEXPORT jstring JNICALL
    Java_com_ndktest_MainActivity_evalJS
    (JNIEnv * env, jobject obj, jstring input){
        duk_context *ctx = duk_create_heap_default();
        const char *nativeString = (*env)->GetStringUTFChars(env, input, 0);
        duk_push_string(ctx, nativeString);
        duk_eval(ctx);
        (*env)->ReleaseStringUTFChars(env, input, nativeString);
        jstring result = (*env)->NewStringUTF(env, duk_to_string(ctx, -1));
        duk_destroy_heap(ctx);
        return result;
    }
    

    Good luck!

提交回复
热议问题