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 "www.google.com", then it wont work. Android will display "web page not available". In the loadUrl() API, we have to give "http://www.google.com", 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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wb = new WebView(this);
wb.setWebViewClient(new HelloWebViewClient());
wb.getSettings().setJavaScriptEnabled(true);
wb.loadUrl("http://www.cricinfo.com");
setContentView(wb);
}

private class HelloWebViewClient extends WebViewClient {

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

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


Then of course, permission is needed.


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

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Difference between SurfaceView and View in Android