Home > Android > Android Hybrid app

Android Hybrid app

                ///webview loads the given url.
		mainWebView.loadUrl("file:///android_asset/mainView.html");
		///to enable javascript functions.
		mainWebView.getSettings().setJavaScriptEnabled(true);
		///open android's function to javascript.
		mainWebView.addJavascriptInterface(this, "DemoActivity");
		///this is used remove two or five pixed gap on right side on view.
		mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

		///to listen javascript's alert function.
		mainWebView.setWebChromeClient(new WebChromeClient(){
			@Override
			public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}
		});

		mainWebView.setWebViewClient(new WebViewClient(){
			
			///listens all external urls.
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return super.shouldOverrideUrlLoading(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}

			///is called when url not found or any other error while loading the page.
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Toast.makeText(_context, description, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				//This is used to ignore ssl error(it will not check ssl certificate and proceeds).
				handler.proceed();
			}

		});

		//to bring focus on web view
		//this enable keyboard on screen 
		mainWebView.requestFocus(View.FOCUS_DOWN);
		mainWebView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_UP:
					if (!v.hasFocus()) {
						v.requestFocus();
					}
					break;
				}
				return false;
			}
		});
///to call javascript function.
mainWebView.loadUrl("javascript:changeValue('"+value+"')");

Javascript file

function showMenu(){
	DemoActivity.showMenu();
}

function hideMenu(name){
	DemoActivity.hideMenu(name);
}

function changeValue(name){
	document.getElementById("messageView").innerHTML = name;
}

You can download the source code from
http://dl.dropbox.com/u/12044966/Demos.zip

Advertisements
Categories: Android Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: