Android and Networking

1.1. Available API’s

Android contains the standard Java network java.net package which can be used to access network resources. Android also contains the Apache HttpClient library.

The base class for HTTP network access in the java.net package is that HttpURLConnection class .

It used to be that the preferred access of the network would be the Apache HttpClient library. September 2011 the Android development team published a blog entry in which they suggest to prefer HttpURLConnection in future Android projects as they constantly improving this implementation.

1.2. Security

To access the Internet your application requires the android.permission.INTERNET permission.

2. Android StrictMode

Within Android development you should avoid performing long running operations on the UI thread. This includes file and network access. StrictMode allows to setup policies in your application to avoid doing incorrect things. As of Android 3.0 (Honeycomb) StrictMode is configured to crash with an NetworkOnMainThreadException exception if network access happens in the UI thread.

While you should do network access in a background thread this tutorial will avoid this to allow the user to learn network access independent from background processing.

If you targeting Android 3.0 or higher you can turn this check of via the following code at beginning of your onCreate() method of your Activity.

 

			
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

 

3. HTTP Clients

3.1. HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This API is recommended by the Android development team to use in newer applications, as this interface get constantly improved.

In the latest version HttpURLConnection supports transparent response compression (via the header Accept-Encoding: gzip, Server Name Indication (extension of SSL and TLS) and a response cache.

The API is relatively straigh forward. For example to retrieve the webpage http://www.vogella.de.

 

				
 URL url = new URL("http://www.vogella.de/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }

 

3.2. Apache HTTP Client

Android contains the Apache HttpClient library. You can either use the DefaultHttpClient or AndroidHttpClient to setup the HTTP client.

DefaultHttpClient is the standard HttpClient and uses the SingleClientConnManager class to handle HTTP connections. SingleClientConnManager is not thread-safe, this means that access to it via several threads will create problems.

The following is an example an HTTP Get request via HttpClient.

 

				
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.vogella.de");
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);
}

 

AndroidHttpClient is a special implementation of DefaultHttpClient which is pre-configured for Android.

AndroidHttpClient was introduced in Android 2.2. An instance can be received via the newInstance() method which allows to specify the user agent as parameter. AndroidHttpClient supports SSL and has utility methods for GZIP compressed data. It registers the ThreadSafeClientConnManager which allows thread safe HTTP access via a managed connection pool. AndroidHttpClient also applied reasonable default for timeouts and socket buffer sizes. It also supports HTTPS by default.

4. Apache HTTPClient example

Create the project de.vogella.android.network.html with the activity ReadWebpage. Change the layout main.xml to the following.

 

			
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </LinearLayout>

    <EditText
        android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <Button
        android:id="@+id/ReadWebPage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClickHandler"
        android:text="Read Webpage" >
    </Button>

    <TextView
        android:id="@+id/pagetext"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical" >
    </TextView>

</LinearLayout>

 

Add the permission android.permission.INTERNET to the AndroidManifest.xml file to allow your application to access the Internet.

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 onPause() method. This method is called whenever the Activity is send into the background.

 

package de.vogella.android.network.html;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import 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. */
	@Overridepublic void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		urlText = (EditText) findViewById(R.id.address);
		textView = (TextView) findViewById(R.id.pagetext);

		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, "http://209.85.229.147");
	}

	@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 R.id.ReadWebPage:
			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;
		}
	}
}

 

5. 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. This requires the ACCESS_NETWORK_STATE permission.

 

			
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;
    }
    return false;
}

 

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

 

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

 

 

 

Tip

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

 

7. Handling network failures

Network connection fail frequently especially for mobile clients. For example if you switch from Wifi to 3G then an existing network connection will break and you need to retry the request.

The Apache HttpClient has an default DefaultHttpRequestRetryHandler object registered which will per default 3 times retry a failed connection. The problem is that switching from one network to another make take a little while and DefaultHttpRequestRetryHandler will retry immediately.

To work around this issue you can implement your own version of DefaultHttpRequestRetryHandler in which you wait a pre-defined time.

For example the implementation could look like:

 

			
AbstractHttpClient client = (AbstractHttpClient) new DefaultHttpClient();

DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler() {

	@Override
	public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
		if (!super.retryRequest(exception, executionCount, context)) {
			return false;
		}
		// Retry but wait a bit
		try {
			Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		return true;

	}
};
client.setHttpRequestRetryHandler(retryHandler);

 

8. Thank you

39 thoughts on “Android and Networking

  1. Great post, I believe blog owners should acquire a lot from this weblog its real user genial. So much excellent information on here :D.

    Like

  2. I like this blog very much so much fantastic information. “The great thing about democracy is that it gives every voter a chance to do something stupid.” by Art Spander.

    Like

  3. I was recommended this web site via my cousin. I’m no longer sure whether this post is written by him as no one else recognize such designated approximately my trouble. You’re incredible! Thank you!

    Like

  4. Just a smiling visitant here to share the love (:, btw great pattern. “The price one pays for pursuing a profession, or calling, is an intimate knowledge of its ugly side.” by James Arthur Baldwin.

    Like

  5. I am now not positive where you are getting your info, however great topic. I needs to spend some time learning much more or figuring out more. Thanks for excellent info I used to be on the lookout for this info for my mission.

    Like

  6. I know this if off topic but I’m looking into starting my own weblog and was curious what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% positive. Any recommendations or advice would be greatly appreciated. Thanks

    Like

  7. cheers for taking the time to discuss this, I feel strongly about it and adore learning a lot more on this topic. If possible, as you gain expertise, could you mind updating your blog with more information? as it is incredibly helpful for me.

    Like

  8. Just wanna remark on few general things, The website layout is perfect, the content is very superb. “The way you treat yourself sets the standard for others.” by Sonya Friedman.

    Like

  9. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

    Like

  10. Excellent site you have here but I was wanting to know if you knew of any user discussion forums that cover the same topics discussed here? I’d really love to be a part of community where I can get suggestions from other experienced people that share the same interest. If you have any recommendations, please let me know. Bless you!

    Like

  11. Very interesting information!Perfect just what I was looking for! “Neurotics build castles in the air, psychotics live in them. My mother cleans them.” by Rita Rudner.

    Like

  12. Some really excellent information, Sword lily I discovered this. “I have hardly ever known a mathematician who was capable of reasoning.” by Plato.

    Like

  13. Nice post . keep up to date the best work And like most people, you probably do not have the expertise to eradicate said virus, making trojan removal about as big a reach as, say, fixing your transmission or tailoring a suit.

    Like

  14. Hey, you used to write wonderful, but the last several posts have been kinda boringÖ I miss your great writings. Past several posts are just a little out of track! come on!

    Like

  15. Outstanding post, I conceive people should learn a lot from this web site its very user friendly. So much good information on here :D.

    Like

  16. Thank you for helping out, fantastic info. “Job dissatisfaction is the number one factor in whether you survive your first heart attack.” by Anthony Robbins.

    Like

  17. Simply wish to say your own article is as incredible. The clarity for your put up is simply great and that i could presume you’re a professional with this subject. Well together with your permission allow me to snatch your feed to remain up to date with approaching post. Thank you a million and please continue the rewarding work.

    Like

  18. Youre so right. Im there with you. Your blog post is definitely worth a read if anyone comes throughout it. Im lucky I did so because now Ive obtained a whole new take a look at this. I didnt realise until this issue was so important and thus universal. You undoubtedly stick it in perspective to me.

    Like

  19. Great post, I think blog owners should acquire a lot from this web site its really user genial. So much excellent info on here :D.

    Like

  20. Valuable information. Lucky me I discovered your web site unintentionally, and I am shocked why this twist of fate did not came about earlier! I bookmarked it.

    Like

  21. Thank you for the sensible critique. Me and my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.

    Like

  22. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100% certain. Any recommendations or advice would be greatly appreciated. Thank you

    Like

  23. Hey…this is a wonderful website buddy!!! i am new here and i found this site very interesting and informative ,, you are a professional blogger…thank you for the post buddy and keep on posting nice stuff like this…and hat off to your work

    Like

  24. Appreciating the dedication you put into your site and detailed information you provide. It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read! I’ve saved your site and I’m including your RSS feeds to my Google account.

    Like

  25. Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any helpful hints for novice blog writers? I’d really appreciate it.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.