Android Combat Simple Tutorial-49th gun (two ways to achieve the network image asynchronous loading)

Source: Internet
Author: User

Loading pictures is a time-consuming task, we need to load asynchronously, there are two ways to load asynchronously: 1. Through the Asynctask class; 2. By handler, let's take a look at how to implement the asynchronous loading of network images in these two ways.

First, Asynctask Way 1.main.xml:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent " >    <imageview        android:id= "@+id/img"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:layout_centerinparent= "true"/></relativelayout>

2.mainactivity.java:
Package Com.example.imageloaderdemo;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.protocolexception;import Java.net.url;import Android.app.activity;import Android.graphics.bitmap;import android.graphics.BitmapFactory; Import Android.os.asynctask;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;public Class Mainactivity extends Activity {private ImageView mimageview;private static String urlstring; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mimageview = (ImageView) Findviewbyid (r.id.img); Urlstring= "http://photocdn.sohu.com/20110927/Img320705637.jpg";//Picture address Myasynctask myasynctask=new myasynctask (); Myasynctask.execute (urlstring);} Class Myasynctask extends Asynctask<string, Void, bitmap> {@Overrideprotected void OnPostExecute (Bitmap result) {Super.onpostexecute (result); Mimageview.setimagebitmap (result);} @Overrideprotected Bitmap doinbackground (String ... params) {Bitmap bitmap=null;try {URL url=new url (params[0]); HttpURLConnection connection= (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (Connection.getresponsecode () ==200) {InputStream inputstream= Connection.getinputstream (); Bitmap=bitmapfactory.decodestream (InputStream);}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (Protocolexception e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();} return bitmap;}}}

3. Summary:1.asynctask<string, Void, bitmap>//three parameters, the first is the incoming URL, the second represents the middle state, where the null is passed in, and the third is the return value2.doinbackground (String ... params) method opens a new thread, aysnctask several other methods are running in the main thread3. In addition to the Doinbackground method, other methods are run in the main thread, so here:
Mimageview.setimagebitmap (result); can be set directly

Run the following example:

The network picture was successfully loaded.
Second, the handler mode asynchronous request bitmap, because the child thread cannot update the main thread UI, so the picture must be rendered by handler way.
The layout file does not change, let's look at Mainactivity.java:
Package Com.example.imageloaderdemo;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.protocolexception;import Java.net.url;import Android.app.activity;import Android.graphics.bitmap;import android.graphics.BitmapFactory; Import Android.os.bundle;import android.os.handler;import android.os.message;import Android.widget.ImageView; public class Mainactivity extends Activity {private ImageView mimageview;private static String urlstring;private Handler H Andler = new Handler () {public void Handlemessage (Message msg) {Bitmap Bitmap = (Bitmap) msg.obj;mimageview.setimagebitmap (bitmap);}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Mimageview = (ImageView) Findviewbyid (r.id.img); URLString = "http://photocdn.sohu.com/20110927/Img320705637.jpg";//Picture address myThread MyThread = new MyThread (); Mythread.start ();//Call Thread}classMyThread extends Thread {@Overridepublic void run () {super.run (); Bitmap Bitmap = null;try {URL url = new URL (urlstring); HttpURLConnection connection = (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout, if (connection.getresponsecode () = =) {InputStream InputStream = Connection.getinputstream (); bitmap = Bitmapfactory.decodestream (InputStream); Message message = new Message (); message.obj = bitmap;handler.sendmessage (message);}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (Protocolexception e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();}}}}

Summary: 1. Open a new thread for network data requests:
Class MyThread extends thread{}
2. Send objects via SendMessage and process data through handlemessage.
Very simple, hope can help beginners.
favorite Friends pay attention to me! Thanks


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat Simple Tutorial-49th gun (two ways to achieve the network image asynchronous loading)

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.