Androidアプリ作ろうと思い立ったはいいがWebアプリしか作ったことないどうしよう派が取り急ぎお茶を濁すアレ

メモです。Androidアプリ側とWebアプリ側でメッセージをやり取りする結構ひどい方法です。loadUrl("javascript:〜とかやるので、涙が出るかも知れません。

package hoge.piyo;

import java.net.URLEncoder;

import hoge.piyo.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

public class MainActivity extends Activity {
	private final String TAG = "hoge.piyo";
	private final String InterfaceName = "android";
	private WebView wv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		wv = (WebView)findViewById(R.id.wv_main);
		wv.addJavascriptInterface(new Object() {

			public void hello(String string) {
				Log.d(TAG, string);
				postMessage(wv, "hello", string);
			}

			private void postMessage(WebView wv, String fn, String msg) {
				wv.loadUrl("javascript:void(onmessage('" + fn + "','" + 
						(msg != null ? encodeURIComponent(msg) : "") + "'))");
			}

			private String encodeURIComponent(String string) {
				return URLEncoder.encode(string).replaceAll("\\+", "%20");
			}

		}, InterfaceName);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.loadUrl("file:///android_asset/main.html");
	}
}
  • assets
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>main</title>
		<link rel="stylesheet" href="main.css" />
		<script src="jquery-1.4.2.min.js"></script>
		<script src="main.js"></script>
	</head>
	<body>
		<h1>main</h1>
		<section>
			<input id="txt" value="こんにちはこんにちは!" />
			<input id="btn" type="button" value="hello" />
		</section>
	</body>
</html>
    • main.js
var Interface = window['android'];
var that = {};

var onmessage = function(fn, msg) {
	that[fn](decodeURIComponent(msg));
};

that.hello = function(msg) {
	$('body').append('<p>' + msg + '</p>');
};

jQuery(function($) {
	$('#btn').click(function() {
		Interface.hello($('#txt').val());
	});
});
  • res
    • layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
<WebView
	android:id="@+id/wv_main"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	/>
</ScrollView>