How to Open a URL from Code


Many apps end up opening a web page at some point. This is often useful to allow changeable information to shown, such as a help screen, that can be maintained on a web server in light of questions from users.

I have come across three ways to do this. The first is to create a android.webkit.WebView and call loadUrl() . You can see this being used in com.android.browser.BrowserActivity where selecting home causes the URL, set up in your settings, to be shown…

            case R.id.homepage_menu_id:
                TabControl.Tab current = mTabControl.getCurrentTab();
                if (current != null) {
                    dismissSubWindow(current);
                    current.getWebView().loadUrl(mSettings.getHomePage());
                }
                break;

The above technique is flexible in that you can even use it to call some JavaScript instead.

But what if the server requires you to use a http POST rather than GET? You can use the commons http client and loadDataWithBaseURL as shown on the Google groups.

A second way to show a URL, but in the built-in web browser rather than within your application, is to use an intent…

Intent myIntent = new Intent(Intent.VIEW_ACTION,
   ContentURI.create("http://www.myurl.com"));
startActivity(myIntent);

Finally,you can also create a TextView with the property android:autoLink=”web”. When the user selects a link in the TextView it will open in the built-in browser application.

Comments are closed.