0% found this document useful (0 votes)
598 views4 pages

Android Networking - Tutorial

This article describes how to access web resources in android. It is based on Eclipse 3.7, java 1. And android 2.3. (Gingerbread)

Uploaded by

murksan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topics covered

  • Android preferences,
  • ConnectivityManager,
  • TextView,
  • User input,
  • XML parsing,
  • LinearLayout,
  • InputStreamReader,
  • Source code,
  • Web resources,
  • AndroidHttpClient
0% found this document useful (0 votes)
598 views4 pages

Android Networking - Tutorial

This article describes how to access web resources in android. It is based on Eclipse 3.7, java 1. And android 2.3. (Gingerbread)

Uploaded by

murksan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topics covered

  • Android preferences,
  • ConnectivityManager,
  • TextView,
  • User input,
  • XML parsing,
  • LinearLayout,
  • InputStreamReader,
  • Source code,
  • Web resources,
  • AndroidHttpClient

Android Networking - Tutorial

[Link]

Android Networking - Tutorial


Lars Vogel
Version 1.2 Copyright 2009 - 2011 Lars Vogel 09.09.2011
Revision History
Revision 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 Networking
1.1. Networking
Android 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 ([Link] package). Even if you use the [Link] 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 "[Link]" permission.

1.2. Android Basics


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

2. URL example
Create the project "[Link]" with the activity "ReadWebpage". Change the layout "[Link]" to the following.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="[Link] android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout> <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/address"></EditText> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read Webpage" android:id="@+id/ReadWebPage" android:onClick="myClickHandler"></Button> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/pagetext" android:scrollbars="vertical"></TextView> </LinearLayout>

Add the permission "[Link]" to "[Link]" to allow your application to access the internet.

1 de 4

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

Android Networking - Tutorial

[Link]

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 [Link]; import [Link]; import [Link]; import import import import import import import import import import import [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link];

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) { [Link](savedInstanceState); setContentView([Link]); urlText = (EditText) findViewById([Link]); textView = (TextView) findViewById([Link]); loadPreferences(); [Link](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 = [Link](URL, "[Link] } @Override protected void onPause() { [Link](); SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); Editor preferenceEditor = [Link](); [Link](URL, [Link]().toString()); // You have to commit otherwise the changes will not be remembered [Link](); } public void myClickHandler(View view) { switch ([Link]()) { case [Link]: try { [Link](""); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet([Link]().toString()); HttpResponse response = [Link](request); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( [Link]().getContent())); String line = ""; while ((line = [Link]()) != null) { [Link](line); } } catch (Exception e) { [Link]("Nay, did not work"); [Link]([Link]()); } break; } } }

3. Check the network availability


Obviously 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 = [Link](); // if no network is available networkInfo will be null, otherwise check if we are connected if (networkInfo != null && [Link]()) { return true;

2 de 4

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

Android Networking - Tutorial

[Link]

} return false; }

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

4. Proxy
This 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.
[Link](getContentResolver(), [Link].HTTP_PROXY, "myproxy:8080");

To change the proxy settings you have to have the permission "[Link].WRITE_SETTINGS" in "[Link]".

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

5. Thank you
Please help me to support this article:

6. Questions and Discussion


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

7. Links and Literature


7.1. Source Code
Source Code of Examples

3 de 4

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

Android Networking - Tutorial

[Link]

7.2. Android Resources


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

7.3. vogella Resources


Eclipse 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.

Common questions

Powered by AI

Android primarily uses the Apache HttpClient library for network operations, which is the preferred way due to its features and integration. The system also allows the use of the java.net package, but internally, it uses the Apache library. Additionally, AndroidHttpClient can be used from Android 2.2 onwards, enabling the specification of user agents and supporting SSL and GZIP compression. Access to network functionality requires the "android.permission.INTERNET" permission in the application's manifest file .

In Android, network resources are accessed using HttpClient for establishing connections and executing HTTP methods such as HttpGet. HttpResponse is used to manage responses from these requests. StreamReader and BufferedReader classes are utilized to read data from the connection, which is then appended and displayed to the user using a TextView within the application .

User preferences in Android are stored using the SharedPreferences system, where data can be committed using an editor object. Preferences are loaded using getSharedPreferences and set via the editor's putString method. When the application pauses, preferences are saved by committing changes, ensuring they are preserved for subsequent sessions .

The XmlPullParser class provides a lightweight and efficient way to parse XML files in Android. It is specifically designed for Android and offers an example in its Javadoc for ease of use. This class allows developers to parse XML data without the overhead of the traditionally heavier SAX and DOM parsers while offering similar functionality .

AndroidHttpClient, introduced with Android 2.2, builds upon DefaultHttpClient by adding features like allowing the designation of custom user agents, SSL support, and handling of GZIP compressed data, which improves performance and security for network communications. It aims for better resource management and performance optimization compared to DefaultHttpClient .

Handling lifecycle events, particularly onPause(), is crucial for managing network operations and user data, as it ensures that data is saved and state is preserved when an application goes into the background. onPause() is used to store the last URL input by the user into SharedPreferences, ensuring this information is retained and reloaded appropriately, which is essential for providing a seamless user experience across sessions .

The document outlines that developers should handle exceptions robustly when performing network operations. Specifically, try-catch blocks are used to manage potential issues during HTTP requests, such as connectivity problems or malformed URLs, by setting error messages in the TextView upon catching exceptions. Developers should anticipate and programmatically handle network variability to ensure stability in application performance .

For an Android application to access the internet, it requires the "android.permission.INTERNET" permission. Additionally, to modify system settings, such as configuring a proxy, the application needs the "android.permission.WRITE_SETTINGS" permission .

Proxies in Android can be configured using the Settings class where the HTTP_PROXY setting is set with the proxy and port details. However, one must be aware that DNS resolving might not work properly behind a proxy, which is a known issue. This requires the "android.permission.WRITE_SETTINGS" permission to make such changes in the application .

The document outlines a method to check network availability using the ConnectivityManager system service. By obtaining the active NetworkInfo object, you can determine network availability by verifying if the networkInfo object is not null and whether it is connected .

You might also like