Android download image from the network implementation

Source: Internet
Author: User

1, the background of the network film request, is one of our most common network requests, no less than the request for json/xml data. Generally to show to the user to see, are not pure text, often are graphic information. In the era of mobile internet, graphics and text often need the latest information, data are obtained from the network.

As we all use, it's a lot of friends in the circle of information, the use of Sina Weibo, the user's icon is also picture information, and so on and so on. Thus, for the image of the request processing, very important, we do the development should be mastered. Today, I'll introduce some of the code I used during the development of my Android project.


2. Analysis of ideas (1) Get a connection to the server
(2) Setting link properties
(3) Getting data from the client
(4) Create picture, close link


3, the network download pictures from the network download pictures, according to our analysis of the HTTP protocol, we know the first to establish a connection, set the request mode and so on. So what are the results? Here, we provide two ways for readers to reference, in practical applications, both have their own appropriate application scenarios.
3.1 Java code is as follows:

Here is a piece of code directly from the server to obtain the image data, provide two ways of return value, one is byte type, one is bitmap type, the latter can be directly applied to the picture resource location, as background image settings.

public class ImageService {/** * get picture * @param path picture path * @return */public static byte[] Getimagebyte (String path) throws IOException {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Set the request method to Getconn.setreadtimeout (5 * 1000); Set request stale time is 5 seconds inputstream InputStream = Conn.getinputstream (); Get picture data via input stream byte[] data = Streamtool.readinputstream (InputStream); Get the binary data of the image return;} /** * Get image * @param path picture path * @return */public static Bitmap getimagebitmap (String path) throws Exception{url URL = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"), if (conn.getresponsecode () = =) {InputStream instream = Conn.getinputstream (); Bitmap Bitmap = Bitmapfactory.decodestream (instream); return Bitmap;} return null;}}

3.2 Error message:

Some people in the low version of the Android system, the direct use of the above code, there is no problem, but in the 2.3 version of the system, there will be a network exception, the error message appears as follows:

Android.os.NetworkOnMainThreadException

In fact, after the Android system upgrade, the normalization of the network, in the higher version of the Android system, no longer allow the main thread to use time-consuming operation, strictly prohibit the use of network requests, such as blocking the main thread of the code fragment.

The solution is also very simple, when the need for network requests, the main thread to open a child thread, so that the time-consuming operation in the child thread, after the finished, and then return the results to the main thread.


Some people in the code, may appear the following error, very strange, no prompt information, can only find the following statement:

Android Java.net.SocketException:Permission denied

This sentence is very convenient to read, meaning that there is no permission, no access to the network, this time, we need to add network access to the Mainfest file permissions on the line. Permissions are as follows:
<uses-permission android:name= "Android.permission.INTERNET"/>


4, a tool class

On top of that, we provide a way to return bytes when we get the picture information, and here we provide a helper class that converts bytes to bitmap. The code is as follows:

byte[] data = Streamtool.read (instream); Bitmap Bitmap = bitmapfactory.decodebytearray (data, 0, data.length);

Provides a helper class, as follows:

public class Streamtool {/** * reads data from stream * @param instream * @return */public static byte[] Read (InputStream instream) throw s Exception{bytearrayoutputstream outputstream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len = 0;wh Ile (len = instream.read (buffer))! =-1) {outputstream.write (buffer, 0, Len);} Instream.close (); return Outputstream.tobytearray ();}}

5. Network Framework

For the loading of network pictures, we should pay attention to some problems, for example, if we are the image application, we should pay attention to the application cache, in order to get a better application experience. However, if the cache is too large to exceed the memory limit of the phone, an oom exception will occur. In network requests, the network framework that we use most often is:
Its source code is publicly available on GitHub and can be downloaded directly if needed:

Https://github.com/nostra13/Android-Universal-Image-Loader

On the network there are a lot of cattle people write blog, which has a detailed analysis of this control, you can go to see:

CSDN's Blog: http://blog.csdn.net/wangjinyu501/article/details/8091623
51CTO's Blog: http://smallwoniu.blog.51cto.com/3911954/1336194


6. Data request

This article does not explain the code for WebView to request Web page data directly, and to return Xml/json codes based on an address.


Android download image from the network implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.