简体   繁体   中英

How to run user-provided, arbitrary code in an android app?

The app I'm coding will need to take user-defined code (the language is not particularly important as the user will never see the language, users will use something like visual scripting) and run that code. The code will need to access libraries written in Java, and create variables and so on. The user provided code will be as complicated as a full program.

I have been looking around for ways to approach this. So far, I've found a few different approaches to this in Java, reflection, javax.script, JavaCompiler, write my own interpreter, among other others. From what I've read reflection probably would not work, according to the android package index, android doesn't have javax.script or JavaCompiler, but there are projects that port Rhino and V8 to android, and I dread writing an interpreter, but will if necessary.

What I want to know is, am I going in the right direction? What would be the best way to approach this?

If language is not important, you can probably try using Javascript instead. Check: http://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String, android.webkit.ValueCallback)

You could expose all the required system function (eg controlling vibration) using the addJavascriptInterface method. This allows you to limit the access to system to only the methods you have exposed.

Another option (probably better) is to use your own interpreter. You will anyway create all the object to allow visual scripting, just define java calls corresponding to each object. This way you can prevent the user from running arbitrary code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM