How to call javascript function from android -Cordova/Phonegap - javascript

I'm using cordova/phonegap to make a Android app and trying to call JavaScript funtion from android/native
My main acitvity:-
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(Url);
// TODO call javascripte from here
}
}
My index.html page
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8">
function myFun(){
alert("call from the ANDROID");
}
</script>
</head>
<body >
</body>
</html>
I want call JavaScript function from phonegap.

try this code
webView.loadUrl("javascript:myFun()");

Related

How can i call android speech-to-text functions from java script code in the web app?

I have a simple web-app, Html page with a simple javascript script in it and an android app that has a webview in it to show the html page and i need to call the android methods from the javascript.
However it works with showToast() when i click on a button in the html
How can i call this speak() method from android in the js code??
public class WebAppInterface {
public MainActivity mainActivity;
Context mContext;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c) {
mContext = c;
}
/**
* Show a toast from the web page
*/
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
/**
* Start the speechToText from the web page
* */
#JavascriptInterface
public void startSpeak(){
mainActivity.speak();
}
}
Here is the speech to text code:
private void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say something");
try{
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
}
catch (Exception e){
Toast.makeText(this,""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode == RESULT_OK && null!=data){
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTextTv.setText(result.get(0));
}
break;
}
}
}
Here is the html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</div>
<hr>
<hr>
<div>
<input type="button" value="Record" onClick="speak()" />
</div>
<div>
<h1>Here goes the generated text:</h1>
<p id="toText"> genText </p>
</div>
<script type="text/javascript">
var genText = 'testing now'
genText = Android.getTextGen();
function speak() {
Android.showToast("start Recording")
Android.startSpeak();
}
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</body>
</html>

Spring boot Rest thymeleaf javascript is not returning HTML

HI I am trying the example given in spring.io getting started guide.
it doesn't show any error but I am not getting HTML view
when I open the link http://localhost:8070/testJson in my browser all it shows is a JSON output like this
{"id":1,"content":"Hello World !"}
But I want it to show a proper HTML view, and I can not use #Controller here, I want to show HTML using Jquery javascript, How can I do that?
here is my controller method
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
This is my Data class
public class TestJsonDto {
private Long id;
private String content;
public TestJsonDto(Long id, String content) {
this.id = id;
this.content = content;
}
public TestJsonDto() {
}
/*
GETTERS AND SETTERS WILL GO HERE
*/
And Below is my application class
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
My Html file is
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and finally, this is my javascript
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
my application.properties is here
server.port=8070
Location of my.js is under src/main/resources/static/my.js
If you want to add a front end that can interact with your API you can structure your app like this:
This code setup your application, including static resources, for instance your resource/static/index.html will be render for root path localhost:8090 unless you wire this path in any controller(make sure root is not implicitly/explicitly user in any other #Controller or annotation).
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
So, a simple way to render the HMTL you want is by putting that HTML at resource/static/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and js should be placed at resource/static/my.js:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
In your rest controller, path /testJson will be attended by getTestJson():
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
So you access localhost:8090 to get the front-end, and thru javascript you access localhost:8090/testJson to get your API.

Android WebView evaluateJavascript Uncaught ReferenceError

Currently I'm trying to figured out which is the best way to invoke javascript from android.
AndroidJSCore. AndroidJSCore
WebView
I've tried AndroidJSCore, it's great. But it would enlarge the apk size.
Then I trying to dive into WebView to invoke javascript. But fail.
Activity look like this:
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private static final String TAG = WebViewActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportZoom(true);
webSettings.setDisplayZoomControls(true);
webView.loadUrl("file:///android_asset/jsWeb/test.html");
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
String test1 = "permissionRegist(\"'function'\", [\"'319609831167500021'\",\"'319609831167500022'\",\"'319609831167500023'\",\"'419609839767500020'\",\"'644731700926740003'\",\"'644731700926740004'\",\"'854885785357389824'\",\"'854995673156816896'\",\"'855001385022918656'\",\"'855009454683459584'\",\"'855298661779902464'\",\"'855303143108513792'\",\"'855347061611171840'\",\"'855356859882803200'\"])";
String test2 = "evalJSExpression()";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(test1, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
webView.evaluateJavascript(test2, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
}
}
});
}
}
there appending files are:
android.js
function permissionRegist(type, list) {
var s_permissionMap = new Map();
s_permissionMap.set(type, list);
}
function evalJSExpression() {
var result = 'dddddd';
return result;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LogicalExpression</title>
<!-- 导入script -->
<script type="text/javascript" src="android.js"></script>
</head>
<body>
<!--<button onClick="permissionRegist()">点击读取文件</button>-->
</body>
</html>
but the result is :
I/chromium: [INFO:CONSOLE(2)] "Uncaught ReferenceError: Map is not defined", source: file:///android_asset/jsWeb/android.js (2)
D/WebViewActivity: null
D/WebViewActivity: "dddddd"
Have you tried https://github.com/mozilla/rhino
here is an example : http://lifeofcoding.com/2015/04/05/Execute-JavaScript-in-Android-without-WebView/
AndroidJSCore is a great lib for android to invoke javascript without WebView.
It seems that Both Native WebView and rhino might have some compilable issues due to the different versions of javascript.
Welcome to contact me about this.
I would find out why when I have time.

JQuery MObile calling Java Method

im trying to do a button that show a alert in the android phone, but nothing happens, the buttons is propertly rendered(i have jquery, jquery mobile, js in assets folder)
...
getWindow().requestFeature(Window.FEATURE_PROGRESS);
WebView webview = new WebView(this);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
setContentView(webview);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file:///android_asset/index.html");
webview.addJavascriptInterface(this,"alerts");
setContentView(webview);
}
public void showAlert() {
AlertDialog alert = new AlertDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(main);
builder.setTitle("Test WORKED?");
builder.setMessage("Yes if you see -_-");
alert = builder.create();
alert.show();
}
the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="file:///android_asset/jquery.mobile-1.4.2.min.css" />
<script src="file:///android_asset/jquery-2.1.0.min.js"></script>
<script src="file:///android_asset/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<button type="submit" onclick="javascript:showalert();">ShowAlert</button>
<script>
$(document).ready(function showalert() {
alerts.showAlert();
)};
</script>
</body>
</html>
and other question is: how do i map this kind of jquery button to do something:
<button class="ui-btn ui-btn-inline">Button</button>
your code has script error.
<script>
$(document).ready(function showalert() {
alerts.showAlert();
)}; //<----- replace please .. });
</script>
and then
add annotation ?
#JavascriptInterface
public void showAlert() {
AlertDialog alert = new AlertDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(main);
builder.setTitle("Test WORKED?");
builder.setMessage("Yes if you see -_-");
alert = builder.create();
alert.show();
}

call android function from javascript

I want to create a button in html and make a call from that button from android through javascript. I have written the following code , which is not working :
I am beginner for android.
public class MainActivity extends Activity {
private static final String PIC_WIDTH = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JsInterface(), "android");
myWebView.loadUrl("file:///android_asset/www/index.html");
}
public class JsInterface{
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
}
in javascript :
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body class="bgClass" id="body" ontouchstart="">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script src="js/myScript.js"></script>
<button id="makeCall" >CALL</button>
<script>
$("#makeCall").click(function(){
console.log("inside click javascript");
console.log(window.android);
android.makeCall();
});
</script>
</body>
</html>
any help??
Make sure your $("#makeCall") method is responding in html.
Then make below changes.It will work.
public class JsInterface{
#JavascriptInterface
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
This annotation allows exposing methods to JavaScript.
I am answering my own question so that it can help others .:)
Finally solved it :
myWebView.setWebViewClient(new MyAppWebViewClient()); it was missing so javascript was not working . And i must add #JavascriptInterface as Hardik Trivedi suggested above.
It is working fine now.
simply adding webView.getSettings().setJavaScriptEnabled(true); worked for me.
must add #JavascriptInterface too.

Categories

Resources