Sunday, September 25, 2016

Is it possible to launch mobile sensor with html5 but only with android webview?

Leave a Comment

I mean without cordova or other framework. I'm pretty sure i need to write Java code and link it somehow with html5 through the android webview. If it is possible, can get a little example how to connect to the camera or other sensor.

2 Answers

Answers 1

Some of the sensors have a JavaScript API such as geolocation, orientation (gyroscope) and the battery. To access the camera you could use MediaDevices.getUserMedia, however, this is still in an experimental stage and is not supported by all Android devices. For more information refer to this link.

Answers 2

Look into JavascriptInterface

https://developer.android.com/reference/android/webkit/WebView.html https://developer.android.com/guide/webapps/webview.html

Specifically, addJavascriptInterface(java.lang.Object, java.lang.String))

@JavascriptInterface class JsInterface {   public void startCamera() { ... } }  WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new JsInterface(), "androidInterface"); 

Basically, add the JavascriptInterface, and enable javascript on the web view. Then in your javascript you can detect if the interface exists like so:

if ("undefined" != typeof androidInterface) {     androidInterface.startCamera(); } 

Now in the Java code for startCamera, you can do whatever native stuff you need done.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment