Android - Web apps

From XennisWiki
Jump to: navigation, search

This article shows an example of using JavaScript in an Android web app. Further information: Building Web Apps in WebView

Example using JavaScript

Java

src/WebAppInterface.java

import android.content.Context;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
 
public class WebAppInterface extends WebView {
 
	private Context mContext;
 
	public WebAppInterface(Context context) {
		super(context);
		mContext = context;
	}
 
	@JavascriptInterface
	public void showToast(String toast) {
		Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
	}
 
	@JavascriptInterface
	public void toLogCat(String paramString) {
		Log.i("WebAppInterface", paramString);
	}	
}

src/MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		
		WebView myWebView;
		myWebView = (WebView) findViewById(R.id.webview);
		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
		myWebView.loadUrl("file:///android_asset/index.html");

		// Call function "myFunction" with parameter "HelloWorld"
		myWebView.loadUrl("javascript: myFunction(HelloWorld);");
	}
}

res/layout/webview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

JavaScript

assets/js/myExample.js

/**
 * Parse output to Android LogCat
 * 
 * @param {String} message
 */
function logCat(message) {
	if (window.Android) {
		window.Android.toLogCat(message);
	} else {
		console.log(message);
	}
}

/**
 * Show toast
 * 
 * @param {String} toast
 */
function showAndroidToast(toast) {
        Android.showToast(toast);
}

/**
 * This function is called by the Java code.
 * 
 * @param {String} toast
 */
function myFunction(message) {
        logCat(message);
}

assets/index.html

<!DOCTYPE html>

<html>
<head>

	<title>My Example</title>
	<meta charset="utf-8" />

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>

	<p>HelloWordl</p>
	
	<script type="text/javascript" src="js/myExample.js</script>

</body>
</html>

See also

External links