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 "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"/>

Monday, January 4, 2010

Exiting Android Application

Suppose in our application, we have a number of activities(say ten) and we need to exit directly from this activity. What we can do is, create an intent and go to the root activity and set flag in the intent as


intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


also, add some extra like boolean to the intent


intent.putExtra("EXIT", true);


Then in root activity, check the value of the boolean and according to that call finish(), in the onCreate() of the root activity


if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}

Androidians