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.
Related
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>
I'm having an application which takes input from a popup dialog.When a user enters a text in the text field of a popup dialog.I need to pass that text to another method ina different class.How can I achieve this. My code is shown below.
viewRoles.jsp
<%#page contentType="text/html" import="com.model.Data" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="bootstrap.css" type="text/css" rel="stylesheet">
<script>
window.onload=function()
{
var el=document.getElementById('btnAddNewRole');
el.onclick=function()
{
var my_text=prompt('Enter text here');
if(my_text){
$.ajax({
url: '/com.model/Data/addRole('+my_text+')',
success: function(my_text){
alert("Inserted")
}, error: function(){
// when got error
}
});
}
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View Roles</title>
</head>
<body><br><br>
<button id="btnAddNewRole" class="btn btn-info">Add New Role</button>
</body>
</html>
Data.java in com.model package
package com.model;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.Session;
#ManagedBean
#SessionScoped
public class Data {
private Roles r;
private HibernateUtil helper;
private Session session;
public void addRole(String roleTitle){
r=new Roles(roleTitle);
session = helper.getSessionFactory().openSession();
session.beginTransaction();
session.save(r);
session.getTransaction().commit();
session.close();
}
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.
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()");
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();
}