How can javascript call functions in android?
This article uses an example to illustrate how to call android functions in javascript. In fact, the method is relatively simple. You only need to call the addJavascriptInterface method to map a java object to a javascript Object.
Android code
- package com.macernow.djstava;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.webkit.JavascriptInterface;
- import android.webkit.WebView;
- public class MainActivity extends ActionBarActivity {
- private static final String TAG = "MainActivity";
- private WebView webView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- webView = (WebView)findViewById(R.id.webView);
- webView.getSettings().setJavaScriptEnabled(true);
- webView.addJavascriptInterface(this,"djstava");
- webView.loadUrl("http://192.168.31.109/demo.html");
- }
- @JavascriptInterface
- public void jsextent() {
- Log.e(TAG,"========== js extension success.");
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- }
WebView must enable javascript. After Android 4.2, @ JavascriptInterface must be added to the java method thrown to javascript.
Layout File
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
- <WebView
- android:id="@+id/webView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- </WebView>
- </RelativeLayout>
Test Call
Call the java method in a javascript script
- window.djstava.jsextent()
Scan the public account