Parent code calling JS in Android Android applications

I am writing an Android Internet application (I will not download APP to the Internet, but install HTML + JS in the applicationโ€™s resources). This means that the GUI will be HTML5, and I will use another "native" stream to read from the microphone and, hopefully, send the "parsed text" to HTML5 / JS code.

Is it possible? In Android code, I see how I can call my own code from JS (and I want the other way around).

http://developer.android.com/guide/webapps/webview.html

+4
source share
1 answer

Yes, Android actually scans.

I am sending an example code from a random example application that I made, but this should force you.

Let's start by assuming that you have a global variable for your web view control class:

String name = "John"; String lastName = "Doe"; 

In the Android class controlling the onCreate() during onCreate() or when setting up the onCreate() ):

 webView.addJavascriptInterface(new JavaScriptInterface(), "android") 

Inner class for your webview control class:

 /** * Sets up the interface for getting access to Latitude and Longitude data * from device **/ private class JavaScriptInterface { public String getName() { return name; } public String getLastName() { return lastName; } public void onJavascriptButtonPushed(String text) { Toast.makeText(WebViewControllingClass.this, "The text of the pressed button is: "+text,Toast.LENGTH_SHORT).show(); } } 

This is for Android, now for use via Javascript:

To get first and last name via JavaScript:

 if (window.android){ name = window.android.getName(); lastName = window.android.getLastName(); } 

If you want to raise a toast, install javascript, whose function will be:

 if (window.android){ window.android.onJavascriptButtonPushed("Hello"); } 

Edit:

I have not tried this, but the search gave it, try it, it should work.

If you want to use it in another direction:

JS:

 function testEcho(message){ window.JSInterface.doEchoTest(message); } 

Android:

 myWebView.loadUrl("javascript:testEcho('Hello World!')"); 
+8
source

Source: https://habr.com/ru/post/1395671/


All Articles