using javascript to trigger android function

Looking to create a button in HTML that triggers a call from an Android device via JavaScript. Here is the code snippet I have tried, but it's not functioning as expected. Please note, I am new to Android development:

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 the JavaScript section:

<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 suggestions or assistance with this issue would be greatly appreciated.

Answer โ„–1

Ensure that your $("#makeCall") function is correctly responding in HTML.

Next, implement the following changes to make it functional:

public class JsInterface{ 
        @JavascriptInterface
        public void makeCall()
        {
            Log.i("Myactivity","inside android makecall");
            // Call any of the public activity methods here....
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:9611396958"));
            startActivity(callIntent);
        }
    }

The annotation above enables the exposure of methods to JavaScript.

Answer โ„–2

After some troubleshooting, I managed to find the solution to my issue and wanted to share it in case it helps anyone else. I finally fixed it by including the line of code

myWebView.setWebViewClient(new MyAppWebViewClient());
which was previously missing, causing the JavaScript to not work properly. Additionally, I followed Hardik Trivedi's suggestion to add @JavascriptInterface. Everything is now functioning correctly.

Answer โ„–3

By including webView.getSettings().setJavaScriptEnabled(true); into my code, I was able to successfully resolve the issue. It is also important to include @JavascriptInterface as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the code behind to reject the href with 'aspx' in the anchor tag?

I am currently working on implementing a calendar control that will display Today's Due and Overdue items in separate accordion sections when a date is selected. To achieve this, I have written the necessary code in the back end and used a style.css f ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature. Though I admit that the site lacks attention to detail, my main ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

What steps can be taken to restrict a user's access to a route through URL parameters?

I am currently developing an Express application that generates and exports a document based on the selections made by a user from two dropdown menus. The values selected in the dropdowns are passed as route parameters after the user clicks a button, trigg ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

Challenges with implementing singleSelect feature in MUI-X DataGrid

Encountering an issue with the singleSelect type on the community version of x-data-grid. The problem arises when attempting to edit a row, where my singleSelect consists of the following data set. Here is how I have configured my DataGrid setup. Although ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "รค" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

Joining arguments beyond argv[2] in a Node.js application

Recently, I received a suggestion from Mykola Borysyuk to use node-optimist. However, the author mentioned that it's deprecated and recommended using Minimist. Even after going through the information, I have a basic understanding. Can someone provid ...

Looping the Connection between Socket.io and Node

I have encountered a problem with my Unity client connecting to my node server using socket.io. While the initial connection is successful and acknowledged, when I try to emit a message to the connected client, the connection seems to get reopened as if a ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

JavaScript ECMAScript 6 - WARNING: "Decorators can only be applied to a class when exporting"

In ECMAScript 6, I am attempting to export a function so that I can import it and utilize it in other files for the sake of writing DRY code. However, an error message is appearing: You can only use decorators on an export when exporting a class (16:0) ...

What is the best way to replace all punctuation with spaces within a large text file using streaming in Node.js?

My goal is to search for all punctuation marks in text files of any size and replace them with spaces using Node.js. Given that the file may be large, I am utilizing read and write streams to break it into chunks before passing it to a function designed ...

Pattern-Based jQuery Selectors

I am looking for a way to use jQuery to select all paragraphs < p > within a < div > that contain time stamps with the following formatting patterns: <p>[22:48]</p> or <p>[22:48 - Subject Line]</p> Can someone provi ...

Guide to using Angular $resource to pass query parameter array

My goal is to implement a feature that allows users to be searched based on multiple tags (an array of tags) using the specified structure: GET '/tags/users?tag[]=test&tag[]=sample' I have managed to make this work on my node server and hav ...

Exploring and accessing elements and nested objects within a dynamically named element in JavaScript using JSON syntax

Receiving a JSON response from an API, here's what the data looks like: [{ "order_id":"1111", "restaurant_id":"ABC", "fullfillment":"Delivery", "order_channel":" ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...