Wednesday, January 6, 2010

Opening a web page in Android

Displaying a web page in android is quite straight forward. But the catchy thing here is the API is quite sensitive, means if we put "", then it wont work. Android will display "web page not available". In the loadUrl() API, we have to give "", then only it will display the web page

If we want to open all web pages through your application, then we need to create an inner class, which extends "WebViewClient" and that should override shouldOverrideUrlLoading().

Then, if we press "back" button, it will return to "Home Scfreen". To got the the last opened web page, we need to override, the onKeyDown(). Here another catchy thing is, if we use onKeyUp() then it won't work. Means it will show "Home Screen" itself. So we need to override onKeyDown().

The full source code is,

public class SampleWebPage extends Activity {

WebView wb = null;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
wb = new WebView(this);
wb.setWebViewClient(new HelloWebViewClient());

private class HelloWebViewClient extends WebViewClient {

public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && wb.canGoBack())
return super.onKeyDown(keyCode, event);

Then of course, permission is needed.

<uses-permisssion android:name="android.permission.INTERNET"/>

No comments:

Post a Comment