Wednesday, April 25, 2018

How to use native android webview in Qt C++ using QAndroidJniObject

Leave a Comment

I would like to use the Android WebView in my qml application. The default WebView object provided uses native rendering but several features are missing (for example the ability to intercept network requests and block them). I know that Qt allows you to call native Java API using QAndroidJniObject. Is it possible to use that to create a Qt wrapper around the native Android WebView? If yes, how can I achieve that?

1 Answers

Answers 1

This is tricky. You basically need to create a new class during runtime that overrides shouldInterceptRequest:

public class SuperDuperUniqueNameForMyWebViewClient extends android.webkit.WebViewClient {     // constructor etc...     @Override     public android.webkit.WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, android.webkit.WebResourceRequest request) {         // implement your logic here     } } 

To create the class dynamically, you muste compile the code on-the-fly in Java:

String source = ...; int result = com.sun.tools.javac.Main.compile(new String[]{source});  // parameter is an array 

Which in Qt C++ gives us this:

QString source = ...;  // Here you need to provide the Java code for your class QAndroidJniObject sourceObject = QAndroidJniObject::fromString(source); jobjectArray sourceObjectArray = sourceObject.object<jobjectArray>();  // this is probably not correct jint result = QAndroidJniObject::callStaticMethod<jint>("com/sun/tools/javac/Main",                                                        "compile"                                                        "([Ljava/lang/String;)I",                                                        jobjectArray); 

After that you should be able create a web view client with your own class and use it:

QAndroidJniObject myWebViewClient{"SuperDuperUniqueNameForMyWebViewClient"}; 

Take all of this with a grain of salt, as it is from the top of my head and I haven't tested it. At the very least it should push you in the right direction, though.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment