Tuesday, March 13, 2012

Opening a website as an Android App

Reference Link : http://developer.android.com/resources/tutorials/views/hello-webview.html

1)Create a simple HelloAndroid application in Eclipse using ADT plugin.

2)Open the res/layout/main.xml file and replace the code with the below snippet :
< ? xml version="1.0" encoding="utf-8"? >
< WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/ >

3)Now update HelloWebView.java file as below in the onCreate() method,
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView
(R.layout.main);

mWebView
= (WebView) findViewById(R.id.webview);
mWebView
.getSettings().setJavaScriptEnabled(true);
mWebView
.loadUrl("http://www.google.com");
}
This will update the view with a Webview widget.

4)Because this application needs access to the Internet, you need to add the appropriate permissions to the Android manifest file. Hence include the below tag in the AndroidManifest.xml file before the Application tag;
< uses-permission android:name="android.permission.INTERNET" / >

5)remove the title bar, with the "NoTitleBar" theme bu including the below attribute in the activity tag
android:theme="@android:style/Theme.NoTitleBar"

6)Now add the below class as a nested class within the Activity class,
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view
.loadUrl(url);
return true;
}
}

7)Set the instance of the above nested class from witing the onCreate() method as below:
mWebView.setWebViewClient(new HelloWebViewClient());

8)To handle the BACK button key press on the device, add the following method inside the HelloWebView Activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView
.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}

Now run your application ...