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

Calculating the quantity of elements within a jQuery array

A JQuery array is proving to be quite problematic. Here's what it looks like, [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32] Unfortunately, there are duplicates present in this array. My goal is to obtain the count of each unique element ...

Tips for implementing a controlled RadioGroup in React: Mapping through an array of values to dynamically populate radio buttons

I have a scenario where I am utilizing a pre-defined set of arrays to populate multiple RadioGroups. The component hierarchy in the codesandbox is structured to resemble that of my actual project. Whenever I select a radio button, I receive an error messa ...

Tips for resolving jQuery conflict problems

I am dealing with a jQuery issue where I have two scripts - one for the slider and the other for a dropdown menu. When I remove one script, the slider works but the dropdown doesn't, and vice versa. I have looked at tutorials online on how to resolve ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

It is essential for each child in a list to be assigned a unique "key" prop to ensure proper rendering, even after the key has been assigned (in Next

Working with Next JS and implementing a sidebar with custom accordions (created as SideAccord.js component). Data is being looped through an array with assigned keys, but still encountering the following error: Warning: Each child in a list should have a u ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

I'm struggling with an issue of being undefined in my React.js project

This code snippet is from my app.js file import React, { useState, useEffect } from "react"; import { v4 as uuid } from "uuid"; import "./App.css"; import Header from "./Header"; import AddContact from "./AddCo ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

Utilize ajax to send both images and text simultaneously

I'm utilizing javascript's 'formData' to transmit image files through ajax. Is there a way to append extra data to formData, like a text string? JS: $("#post-image").on("click", function(){ $.ajax({ url: "../../build/ajaxe ...

Node.js command-line interface for chat application

Can someone help me figure out the best method for creating a command line interface chat app using nodejs? I'm considering using http and possibly phantomjs to display it in the terminal, but I have a feeling there's a more efficient approach. A ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

Tips on restricting users to choose dates that are later than the current date

Currently, I am working with Vue3 using the options API. After reviewing this StackBlitz, my question is regarding how to correctly set the :max value for a date-picker. Even though I have assigned :max as new Date(), I am still able to select dates that ...

Is it possible to modify the contents within the JSP div tag without replacing them through an AJAX call?

In my JSP, I face a scenario where there is a div tag with scriptlet content that pulls data from the database every time a request is received from the server. Previously, I was refreshing the entire page with each update, which not only loaded all the re ...

Having trouble loading HTML content from another file

Here is the code snippet in question: <script> var load = function load_home(){ document.getElementById("content").innerHTML='<object type="type/html" data="/linker/templates/button.html" ></object>'; } </script> ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...