Android message mechanism Application

Source: Internet
Author: User

Android message mechanism Application

You can use an example to familiarize yourself with the use of the Android message mechanism. In this example, there is an EditText, ImageView, and a Button in the Main Line. after entering the image address in EditText, click the Button, the main thread sends a message request to the background thread to download the image. After the background thread downloads the image, it sends a message request to the main thread to update the UI to display the downloaded image. Through this example, we are familiar with the use of the message mechanism, and understand the two-way transmission of Handler. The final effect is as follows:

The main thread sends messages to the background thread.

The background thread sends messages to the main thread.

Sample source code

Layout file res/layout/activity_main.xml


  
      
       
   
      
   

MainActivity is used to display the interface. As the main thread, it receives and processes the messages on the update interface.

Package com. wuhui. testhandler; import android. app. activity; import android. graphics. bitmap; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. imageView;/*** Created by Administrator on 2015/5/6. */public class MainActivity extends Activity {private EditText mEditText; Private Button mButton; private ImageView mImageView; private Downloader mDownloader; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mEditText = (EditText) findViewById (R. id. edittext_url); mImageView = (ImageView) findViewById (R. id. imageview_image);/* Create a Handler associated with the main thread and pass it as a constructor parameter to the Downloader object */mDownl Oader = new Downloader (new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); switch (msg. what) {case Downloader. MESSAGE_DOWNLOAD: if (msg. obj! = Null) {Bitmap bitmap = (Bitmap) msg. obj; // update the image mImageView. setImageBitmap (bitmap) ;}break; default: break ;}}); mDownloader. start (); // start the background thread mDownloader. getloton (); // ensure that the message loop in the background thread initializes mButton = (Button) findViewById (R. id. button_download); mButton. setOnClickListener (new Button. onClickListener () {@ Override public void onClick (View v) {// download the image mDownloader. downloadImage (mEditText. getText (). toString ());}});}}

The Downloader class is a background thread inherited from the HandlerThread class, so it has a message loop. The Downloader class is responsible for receiving and processing the messages for downloading images.

Package com. wuhui. testhandler; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. handler; import android. OS. handlerThread; import android. OS. message; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL;/*** Created by Administrator on 2 015/5/6. */public class Downloader extends HandlerThread {private static final String mName = "Downloader"; public static final int MESSAGE_DOWNLOAD = 1; private Handler mHandler; // Handler private Handler mResponseHandler of the current thread; // Handler Downloader (Handler handler) {super (mName); mResponseHandler = handler; // Save the Handler of the main thread} // This function is called before the message loop starts @ Override protected void onLooperPrepared () {Super. onLooperPrepared (); // create the current thread's Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); String imageUrl = (String) msg. obj; // download the image handleDownloadImage (imageUrl) ;}};} public void downloadImage (String imageUrl) {/*** here handleDownloadImage is not called directly to download the image, but a message is sent, * This method can also be returned immediately if multiple images need to be downloaded consecutively. * The background thread downloads images in sequence based on requests in the message queue. ** // Send the message of the downloaded image to the Message Queue mHandler of the current thread. obtainMessage (MESSAGE_DOWNLOAD, imageUrl ). sendToTarget ();} private void handleDownloadImage (String imageUrl) {try {URL url = new URL (imageUrl); HttpURLConnection connection = (HttpURLConnection) url. openConnection (); connection. connect (); if (connection. getResponseCode ()! = HttpURLConnection. HTTP_ OK) {return;} InputStream in = connection. getInputStream (); byte [] buffer = new byte [512]; int readSize = 0; ByteArrayOutputStream out = new ByteArrayOutputStream (); while (readSize = in. read (buffer)> 0) {out. write (buffer, 0, readSize);} out. close (); byte [] bitmapBytes = out. toByteArray (); // decodes the Bitmap bitmap = BitmapFactory from the downloaded byte data. decodeByteArray (bitmapBytes, 0, bitmapBytes. length); // send a message to the main thread. The downloaded image is used as the Message Parameter mResponseHandler. obtainMessage (MESSAGE_DOWNLOAD, bitmap ). sendToTarget ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

The above is all the code.

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.