Android Network Learning: Getting server Images

Source: Internet
Author: User

Android Network Learning: Getting server Images

First, you need to build a Tomcat server, and then test whether images on the server can be downloaded normally using a PC browser.

We can see that the image data on the server can be accessed normally. Image address: http: // localhost: 8080/meinv.jpg

So how can we download images from the Internet on Android?

Code for getting a network image directly:

 

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void click (View v) {// 1: confirm the URL String path = http: // localhost: 8080/meinv.jpg; try {// 2: encapsulate the URL as a URL object url = new URL (path); // 3: Get the connection object between the client and the server. At this time, no connection is established. HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // 4: Initialize the connection object conn. setRequestMethod (GET); // set connection timeout conn. setConnectTimeout (5000); // set the read timeout conn. setReadTimeout (5000); // 5: initiate a request and establish a connection with the server conn. connect (); // if the response code is 200, the request is successful if (conn. getResponseCode () = 200) {// get the InputStream is = conn in the response header of the server. getInputStream (); // read the data in the stream and construct the bitmap Bitmap bm = BitmapFactory. decodeStream (is); // displayed on the Interface ImageView imageView = (ImageView) findViewById (R. id. lv); imageView. setImageBitmap (bm) ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

Running results:

 

Printing from the console can be a warning: the network works abnormally in the main thread.

The above warning is introduced after 4.0. If a network task is in the main thread, a warning is reported. Therefore, we need to enable a thread to execute network tasks.

 

The modified code is as follows:

 

Public void click (View v) {// enable a Thread thread Thread = new Thread () {@ Override public void run () {// TODO Auto-generated method stub // 1: confirm the URL String path = http: // localhost: 8080/meinv.jpg; try {// 2: encapsulate the URL as a URL object url = new URL (path); // 3: Get the connection object between the client and the server. At this time, no connection is established. HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // 4: Initialize the connection object conn. setRequestMethod (GET); // set connection timeout conn. setConnectTimeout (5000); // set the read timeout conn. setReadTimeout (5000); // 5: initiate a request and establish a connection with the server conn. connect (); // if the response code is 200, the request is successful if (conn. getResponseCode () = 200) {// get the InputStream is = conn in the response header of the server. getInputStream (); // read the data in the stream and construct the bitmap Bitmap bm = BitmapFactory. decodeStream (is); // displayed on the Interface ImageView imageView = (ImageView) findViewById (R. id. lv); imageView. setImageBitmap (bm) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}}; // start the thread task thread. start ();}

Run it again to see the effect:

 

Another warning is reported: The call error thread is abnormal. That is to say, the view can be called only when the view is created. To put it bluntly, only the main thread (UI thread) can update the UI. Other threads cannot update the UI at will.

If you need to update the UI, only the main thread can update the UI. How can other threads tell the main thread to update the UI? This requires the introduction of another knowledge point: Message

 

If other threads need to update the UI, a message is sent to the main thread. After receiving the message, the main thread automatically updates the UI.

 

Code modified:

 

If (conn. getResponseCode () = 200) {// get the InputStream is = conn in the response header of the server. getInputStream (); // read the data in the stream and construct the bitmap Bitmap bm = BitmapFactory. decodeStream (is); // The Message msg = handler that updates the UI. obtainMessage (); msg. obj = bm; handler. sendMessage (msg); // displayed on the Interface // ImageView imageView = (ImageView) findViewById (R. id. lv); // imageView. setImageBitmap (bm );}

Add Handler, that is, handle for processing messages.

 

 

Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {// update UIImageView imageView = (ImageView) findViewById (R. id. lv); imageView. setImageBitmap (Bitmap) msg. obj );};};

Run it again to see the effect:

 

The image is displayed normally.

Modify the code to add the processing logic for failed retrieval.

 

If (conn. getResponseCode () = 200) {// get the InputStream is = conn in the response header of the server. getInputStream (); // read the data in the stream and construct the bitmap Bitmap bm = BitmapFactory. decodeStream (is); // The Message msg = handler that updates the UI. obtainMessage (); msg. obj = bm; msg. what = GET_ OK; handler. sendMessage (msg); // displayed on the Interface // ImageView imageView = (ImageView) findViewById (R. id. lv); // imageView. setImageBitmap (bm);} else {// send Message msg = handler. obtainMessage (); msg. what = GET_ERROR; handler. sendMessage (msg );}

Message Processing Process:

 

 

Static final int GET_ERROR = 0; static final int GET_ OK = 1; Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {// update UIswitch (msg. what) {case GET_ OK: ImageView imageView = (ImageView) findViewById (R. id. lv); imageView. setImageBitmap (Bitmap) msg. obj); break; case GET_ERROR: Toast. makeText (MainActivity. this, Access failed !, Toast. LENGTH_SHORT). show (); break; default: break ;}};};

We can change the address to an error to show the effect.

 

A brief description of the message mechanism:

1: when a message is generated, the MessageQueue and loopback object are used)

2: The purpose of the message polling object is to continuously check whether there is any care in the message queue. If there is a message, the message polling device will send the message object to the message processor (Handler ), the processor calls the handleMessage method to process the message. The handleMessage method runs in the main thread, so you can refresh the ui

 

However, in common applications, for example, a large number of images in the circle of friends, the first time they are browsed, they are buffered to the local device, and the second time they are browsed, they can be directly read from the local device. Let's implement the following:

 

Public void click (View v) {// specify the File path final file File = new File (getCacheDir (), info.jpg); // if the file exists, open if (file. exists () {System. out. println (read from the cache); Bitmap bm = BitmapFactory. decodeFile (file. getAbsolutePath (); ImageView imageView = (ImageView) findViewById (R. id. lv); imageView. setImageBitmap (bm);} else {System. out. println (downloaded from the Internet); // enable a Thread thread Thread = new Thread () {@ Override public void run () {// TODO Auto-generated method stub // 1: confirm the URL String path = http: // 192.168.1.109: 8080/meinv.jpg; try {// 2: encapsulate the URL as a URL object url = new URL (path); // 3: Get the connection object between the client and the server. At this time, no connection is established. HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // 4: Initialize the connection object conn. setRequestMethod (GET); // set connection timeout conn. setConnectTimeout (5000); // set the read timeout conn. setReadTimeout (5000); // 5: initiate a request and establish a connection with the server conn. connect (); // If the response code Is 200, indicating that the request is successful if (conn. getResponseCode () = 200) {// get the InputStream is = conn in the response header of the server. getInputStream (); // read the data returned by the server in the stream, write the data to the local device, and buffer FileOutputStream fos = new FileOutputStream (file ); byte [] B = new byte [1024]; int len = 0; while (len = is. read (B ))! =-1) {fos. write (B, 0, len);} fos. close (); is. close (); // load the image Bitmap bm = BitmapFactory locally. decodeFile (file. getAbsolutePath (); // read the data in the stream and construct the bitmap Bitmap. // bitmap bm = BitmapFactory. decodeStream (is); // The Message msg = handler that updates the UI. obtainMessage (); msg. obj = bm; msg. what = GET_ OK; handler. sendMessage (msg); // displayed on the Interface // ImageView imageView = (ImageView) findViewById (R. id. lv); // imageView. setImageBitmap (bm);} else {// send Message msg = handler. obtainMessage (); msg. what = GET_ERROR; handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}}; // start the thread task thread. start ();}}

The above shows how to get image files from the local buffer.

 

At the first run time: the cacheunder the package file name will contain the info.jpg file.

Buffer files

When the exit comes in again, it will be obtained directly from the buffer.

 

 

Here is a simple introduction to getting files from the network.

 

 

Related Article

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.