Home > database >  Raw tcp socket inside android webview
Raw tcp socket inside android webview

Time:02-24

Intro

I'm working on an Android app that allows non-programmers to program an educational robot using a visual programming language (Blockly based). This robot runs a lua virtual machine and can set up his own wifi network which I will connect to from my Android device.

The problem

I need to send the code to the robot and I need to do this from inside the Android webview because it's important that the user can continue to see the block-based program while the robot executes it and sends back feedback to the mobile device (which will highlight the code blocks being executed in real time). So basically: I need to send and receive data from inside an Android webview through a raw tcp socket using my own communication protocol.

What have I tried?

I've been searching information on how to solve this. So far I've learnt:

  • Plain javascript: you can only use websockets which work with http protocol and don't support my custom protocol.
  • React native: I think it would enable me to solve this since it's node.js based and node.js offers libraries that support raw sockets. (Discarded because apparently react native doesn't use webview)
  • Androidjs: it's a framework that apparently would let me use node.js on my android app, the problem with this framework is that it doesn't seem to be very popular and the github seems to be a little abandoned, not sure if I should use this. Another problem is that I am not 100% clear on if it allows me use node.js packages inside the android webview.

CodePudding user response:

I didn't find a way to use raw tcp sockets inside the webview.

However I was able to work around this problem binding a javascript interface to my webview which allows communication between the webview and the interface (a Java class), then in the interface I implemented the tcp socket easily since it's Java.

JavascriptInterface info: https://developer.android.com/guide/webapps/webview.html#BindingJavaScript

The way I used to communicate from Android to the webview was defining a javascript function in the js file running inside my webview, let's call it "myJsFunction()", which will be called using the WebView's loadurl() method, like this:

WebView myWebView = ...;
myWebView.loadUrl("javascript:myJsFunction()");
  • Related