Android Networking - Tutorial

  • Published on

  • View

  • Download


Android Networking - Tutorial

Android Networking - TutorialLars VogelVersion 1.2 Copyright 2009 - 2011 Lars Vogel 09.09.2011Revision HistoryRevision 0.1 Created Revision 0.2 - 1.1 bug fixes and enhancements 30.08.2010 - 09.09.2011 Lars Vogel 19.07.2010 Lars Vogel

Networking with Android This article describes how to access web resources in Android. It is based on Eclipse 3.7, Java 1.6 and Android 2.3.3 (Gingerbread). Table of Contents 1. Android Networking 1.1. Networking 1.2. Android Basics 2. URL example 3. Check the network availability 4. Proxy 5. Thank you 6. Questions and Discussion 7. Links and Literature 7.1. Source Code 7.2. Android Resources 7.3. vogella Resources

1. Android Networking1.1. NetworkingAndroid contains the Apache HttpClient library and this library is the preferred way of performing network operations in Android. Android also allows to access the network via the standard Java Networking API ( package). Even if you use the package Android will internally use the Apache library. For XML parsing Android provides the class "XmlPullParser" which is an Android specific XML parser. The standard SAX and DOM XML parsers are also available on Android. The Javadoc of "XmlPullParser" gives a nice example how you can use this library. As of Android 2.2 you can also use the AndroidHttpClient. An instance can be received via newInstance() which allows to specify the user agent. AndroidHttpClient supports SSL and has utility methods for GZIP compressed data. To access the internet your application requires the "android.permission.INTERNET" permission.

1.2. Android BasicsThe following assumes that you have already basic knowledge in Android development .

2. URL exampleCreate the project "" with the activity "ReadWebpage". Change the layout "main.xml" to the following.

Add the permission "android.permission.INTERNET" to "AndroidManifest.xml" to allow your application to access the internet.

1 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

Create the following code to read a webpage and show the HTML code in the TextView. This example also demonstrate the usage of Android preferences to store user data. The URL which the user has typed is stored in the preferences in the method onPause(). This method is called whenever the Activity is send into the background.package; import; import; import import import import import import import import import import import org.apache.http.HttpResponse; org.apache.http.client.HttpClient; org.apache.http.client.methods.HttpGet; org.apache.http.impl.client.DefaultHttpClient;; android.content.SharedPreferences; android.content.SharedPreferences.Editor; android.os.Bundle; android.view.View; android.widget.EditText; android.widget.TextView;

public class ReadWebpage extends Activity { private static final String PREFERENCES = "PREFERENCES"; private static final String URL = "url"; private String lastUrl; private EditText urlText; private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); urlText = (EditText) findViewById(; textView = (TextView) findViewById(; loadPreferences(); urlText.setText(lastUrl); } /** * Demonstrates loading of preferences The last value in the URL string will * be loaded */ private void loadPreferences() { SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); // Set this to the Google Homepage lastUrl = preferences.getString(URL, ""); } @Override protected void onPause() { super.onPause(); SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); Editor preferenceEditor = preferences.edit(); preferenceEditor.putString(URL, urlText.getText().toString()); // You have to commit otherwise the changes will not be remembered preferenceEditor.commit(); } public void myClickHandler(View view) { switch (view.getId()) { case try { textView.setText(""); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlText.getText().toString()); HttpResponse response = client.execute(request); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { textView.append(line); } } catch (Exception e) { System.out.println("Nay, did not work"); textView.setText(e.getMessage()); } break; } } }

3. Check the network availabilityObviously the network on an Android device is not always available. You can check the network is currently available via the following code.public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null, otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true;

2 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

} return false; }

Android Apps Dev Group Discuss Android Apps creation, development, and programming. Gps Software Free Technical Search Engine Search Thousands of Catalogs Today Beyondsoft A leading IT services company with Global Delivery Centers.

4. ProxyThis chapter is only relevant for you if you are testing with the Android similator behind a proxy. In class you are behind a proxy during your testing you can set the proxy via the class "Settings". For example you could add the following line to your onCreate method in your activity.Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080");

To change the proxy settings you have to have the permission "android.permission.WRITE_SETTINGS" in "AndroidManifest.xml".

It seems that DNS resolving doesn't work behind a proxy. See Bug 2764

5. Thank youPlease help me to support this article:

6. Questions and DiscussionBefore posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the Google Group . I have created a short list how to create good questions which might also help you.

7. Links and Literature7.1. Source CodeSource Code of Examples

3 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

7.2. Android ResourcesIntroduction to Android Development Android Location API and Google Maps Android Homepage Crest Framework to access rest services, works also on Android

7.3. vogella ResourcesEclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system

4 de 4

05/09/2011 09:06 p.m.