Android Handler detailed (interview must ask) _android

Source: Internet
Author: User
Tags message queue static class

Handler is known as the "Message Processor" in Android and is more commonly used in multithreading.

Handler provides an asynchronous message processing mechanism for Android that returns immediately after sending a message (SendMessage) to a message queue and blocks when reading messages from a message queue, where the public in handler is executed when reading messages from message queues The Void Handlemessage (Message msg) method, so you should use an anonymous inner class to override the method when you create the handler, write the action read to the messages in the method, and use the Obtainmessage () of handler to get the message object.

Handler Relationship to Threads:

After the Runnable object is placed in the handler thread queue using the handler post method, the runnable execution does not actually open the thread alone, but is still executed in the current activity thread. Handler just called the Run method of the Runnable object.

What is bundle:

Bundle is a special map that is a tool for passing information, its keys can only be of type string, and values are only common basic data types.

Handler Internal Realization principle

Handler implementation Mechanism:

1,message object that represents a message to be delivered, using a linked list data structure to implement a message pool for reuse,
Avoid creating a large number of message objects, resulting in wasted memory
2,messagequeue object that holds message queues for message objects, advanced first out principle
The 3,looper object is responsible for managing Message Queuing for the current thread
The 4,handler object is responsible for the push of the message into the message queue and the receipt of messages Looper from the message queue

Handler memory leak problem (activity has exited and handler not exited, which could result in memory leaks)

1, when you define an inner class, you have a reference to the external class object by default, so it is a good idea to define a static inner class when using the inner class
2, the strength of the reference: strong reference → soft reference → weak reference

Below use to obtain the network picture code to explain handler basic use

Package Com.example.uri;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.lang.ref.WeakReference;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.app.Activity;
Import Android.content.Context;
Import android.content.Intent;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.view.Menu;
Import Android.view.View;
Import Android.widget.ImageView; /** * * Access to the network operation, must be placed in the worker thread complete */public class Mainactivity extends activities {private static final int loadsuccess=0x1 P
Rivate Static ImageView IV;
Private final MyHandler handler=new MyHandler (this); @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
iv= (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); private static class MyHandler extends handler{private final weakreference<mAinactivity> WeakReference;
Public MyHandler (mainactivity mainactivity) {weakreference=new weakreference<mainactivity> (MainActivity);} public void Handlemessage (message msg) {mainactivity mainactivity=weakreference.get (); if (mainactivity!=null) {switch
(msg.what) {case LOADSUCCESS:MainActivity.iv.setImageBitmap (Bitmap) msg.obj); } public void Geturl (View v) {/*intent Intent = new Intent (Intent.action_view, Uri.parse ("http://www.baidu.com")); start Activity (intent); /New Thread (new Runnable () {@Override public void run () {try {URL url=new url ("HTTP://IMG2.3LIAN.COM/IMG2007/10/28/12
3.jpg ");
InputStream In=url.openstream ();
Bitmap Bitmap=bitmapfactory.decodestream (in);
Message message= handler.obtainmessage (loadsuccess, bitmap);
Handler.sendmessage (message); catch (Malformedurlexception e) {//Todo automatically generated catch block E.printstacktrace ();} catch (IOException e) {//TODO automatically generated cat
CH Block e.printstacktrace ();
}}). Start (); }
}

How to enable handler to open a new thread when executing runnable:

1, the first generation of a Handlerthread object, the implementation of the use of looper to process Message Queuing functions, this class is provided by the Android application framework
Handlerthread handlerthread = new Handlerthread ("Handler_thread");

2. Before using the Getlooper () method of Handlerthread, you must first invoke the start () of the class.
Handlerthread. Start ();

3, according to this Handlerthread object to get the Looper object.

4. Create a custom subclass that inherits from the handler class, in which you implement a constructor for a parameter of Looper object, which invokes the constructor of the parent class.

5, using the third step of the Looper object to create a custom handler subclass of the object, and then send the message to the handler message queue, handler replication Handlemessage () will be executed to process messages in Message Queuing.

Above to give you detailed introduction of the Android handler related knowledge, hope to help you!

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.