A summary of Handler usage and a summary of Handler usage

Source: Internet
Author: User

A summary of Handler usage and a summary of Handler usage

* *********************************** MHandler. postDelayed (image polling) and mHandler. post (with the new UI) ************************************

Activity_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"    tools:context="com.example.handlerdemo.MainActivity" >    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <ImageView        android:id="@+id/imageView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_below="@+id/tv"        android:layout_marginRight="52dp"        android:layout_marginTop="84dp"        android:src="@drawable/ic_launcher" /></RelativeLayout>

MainActivity

Package com. example. handlerdemo; import android. r. mipmap; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. view. menu; import android. view. menuItem; import android. widget. imageView; import android. widget. textView; public class MainActivity extends Activity {private TextView TV; private Handler mHandler = new Handler (); private ImageView mImageView; private int images [] = {R. drawable. ic_launcher, R. drawable. ic_launcher1, R. drawable. ic_launcher2}; // Image Location private int index; private MyRun myRun = new MyRun (); class MyRun implements Runnable {@ Overridepublic void run () {index ++; index = index % 3; mImageView. setImageResource (images [index]);/** mHandler. post Updates the UI. After 1 second, handler repeatedly sends the Runnable object */mHandler. postDelayed (myRun, 1000) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);/*** Handler is bound to the main thread and mHandler is in the thread division. post Updates the UI. * handler can distribute Message objects and Runnable objects to the main thread */TV = (TextView) findViewById (R. id. TV); new Thread () {public void run () {mHandler. post (new Runnable () {@ Overridepublic void run () {TV. setText ("xxx ");}});};}. start ();/*** indicates the timer function. Handler is bound to the main thread. In the main thread, handler directly sends the Runnable object */mImageView = (ImageView) after 1 second) findViewById (R. id. imageView); mHandler. postDelayed (myRun, 1000 );}}
</Pre> <pre name = "code" class = "java"> *********************** ****************** **************
The layout file has only one textview.
<Pre name = "code" class = "java"> package com. example. handlerdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. handlerThread; import android. OS. logoff; import android. OS. message; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {private TextView textView; private Handler handler = new Handler () {public void handleMessage (Message msg) {textView. setText ("ok2"); Log. e ("TAG", "" + msg. what); // 1 };};/***** method 1 */private void handler1 () {handler. post (new Runnable () {@ Overridepublic void run () {textView. setText ("ok1") ;}}) ;}/ *** method 2 */private void handler2 () {handler. sendEmptyMessage (1);}/*** method 3 */private void updateUI () {runOnUiThread (new Runnable () {@ Overridepublic void run () {textView. setText ("ok3") ;}}) ;}/ *** Method 4 */private void viewUpdateUi () {textView. post (new Runnable () {@ Overridepublic void run () {textView. setText ("ok4") ;}}) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textView);/*** Method 5 */handler. post (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtextView. setText ("ok5") ;}}); new Thread () {public void run () {try {Thread. sleep (1000); // handler1 (); // handler2 (); // updateUI (); // viewUpdateUi ();} catch (InterruptedException e) {e. printStackTrace ();}};}. start ();}}


 

*********************************** Create a message, two message sending Methods ********************************** *****

The Ui remains unchanged, and the xml layout of the previous example is reused.

MainActivity

Package com. example. handlerdemo; import android. r. mipmap; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. menu; import android. view. menuItem; import android. widget. imageView; import android. widget. textView; public class MainActivity extends Activity {private TextView TV; private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {TV. setText ("" + msg. arg1 + ">>>" + msg. arg2 + "" + msg. obj) ;}}; private ImageView mImageView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. TV); mImageView = (ImageView) findViewById (R. id. imageView); new Thread () {public void run () {try {Thread. sleep (2000); Message message = mHandler. obtainMessage (); // Message message = new Message (); or you can use this to create msgmessage. arg1 = 88; message. arg2 = 100; Person person = new Person (); person. age = 10; person. name = "wyf"; message. obj = person; message. sendToTarget (); // mHandler. sendMessage (message); or you can use this to send a message} catch (InterruptedException e) {e. printStackTrace ();}};}. start () ;}class Person {public int age; public String name; @ Overridepublic String toString () {return "Person [age =" + age + ", name = "+ name +"] ";}}

*********************************** Meaning of removing a message and return value of handleMessage **************************************** ***************

Activity_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"    tools:context="com.example.handlerdemo.MainActivity" >    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <ImageView        android:id="@+id/imageView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_below="@+id/tv"        android:layout_marginRight="52dp"        android:layout_marginTop="84dp"        android:src="@drawable/ic_launcher" />    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/imageView"        android:layout_marginTop="32dp"        android:layout_toLeftOf="@+id/imageView"        android:text="Button" /></RelativeLayout>

MainActivity

Package com. example. handlerdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity implements OnClickListener {private TextView TV; private ImageView mImageView; private Button button; private Handler mHandler = new Handler (new Handler. callback () {@ Overridepublic boolean handleMessage (Message msg) {Toast. makeText (MainActivity. this, "1", 0 ). show (); // here is false. If 1 2 is true, only 1 return false; }}) {@ Overridepublic void handleMessage (Message msg) is displayed) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, "2", 0 ). show () ;}}; private int images [] = {R. drawable. ic_launcher, R. drawable. ic_launcher1, R. drawable. ic_launcher2}; // Image Location private int index; private MyRun myRun = new MyRun (); class MyRun implements Runnable {@ Overridepublic void run () {index ++; index = index % 3; mImageView. setImageResource (images [index]);/** mHandler. post Updates the UI. After 1 second, handler repeatedly sends the Runnable object */mHandler. postDelayed (myRun, 1000) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. TV); mImageView = (ImageView) findViewById (R. id. imageView); mHandler. postDelayed (myRun, 1000); button = (Button) findViewById (R. id. button); button. setOnClickListener (this) ;}@ Overridepublic void onClick (View v) {// clear message mHandler. removeCallbacks (myRun); mHandler. sendEmptyMessage (1 );}}

************************************ Handler advanced -- handler can be executed in the main thread, you can also run the -- thread-related handler **************************** ***********

Logoff contains a MessageQueue
Logoff. logoff endless loop, constantly Retrieving messages from MessageQueue
And process messages
Inside the Handler, you can find the logoff and MessageQueue.
Then, the message is sent to the MessageQueue queue.

Summary:
Handler is responsible for sending messages, and logoff is responsible for receiving messages sent by handler
And directly send the message back to handler.

// ActivityThread is responsible for creating all the activities
// Create the Main thread
// Set and get variable information in ThreadLocal thread, such as Logoff
// Logoff exists in the thread
// Create a MessageQuene

Package com. example. handlerdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. util. log; import android. widget. textView; public class MainActivity extends Activity {private Handler UIHandler = new Handler () {public void handleMessage (Message msg) {Log. e ("UI", "" + Thread. currentThread () ;};}; private MyThread myThread; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); TextView textView = new TextView (this); textView. setText ("hello"); setContentView (textView); myThread = new MyThread (); myThread. start (); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} // The Sub-thread handler sends a message and executes myThread in the sub-thread. mHandler. sendEmptyMessage (1); // The main thread handler sends a message and executes UIHandler in the main thread. sendEmptyMessage (1);}/*** creates a subthread with the mHandler attribute **/class MyThread extends Thread {public Handler mHandler; @ Overridepublic void run () {super. run (); logoff. prepare (); mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubsuper. handleMessage (msg); Log. e ("Thread", "" + Thread. currentThread () ;}}; Looper. loop ();}}}

* *********************************** HandlerThread ** ***********************************

package com.example.handlerdemo;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.HandlerThread;import android.os.Looper;import android.os.Message;import android.util.Log;import android.widget.TextView;public class MainActivity extends Activity {private TextView textView;private HandlerThread thread;private Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);textView = new TextView(this);textView.setText("hello");setContentView(textView);thread = new HandlerThread("handler thread");thread.start();handler = new Handler(thread.getLooper()){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);Log.e("TAG", ""+Thread.currentThread());}};handler.sendEmptyMessage(1);}}

* ************************************ Main thread thread message interaction ************************************* ****

The layout file has only one Button for sending messages.

Package com. example. handlerdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. handlerThread; import android. OS. logoff; import android. OS. message; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity implements OnClickListener {private Button sendButton;/*** handler of the main thread */private Handler handler = new Handler () {public void handleMessage (Message msg) {Message message = new Message (); Log. e ("TAG", "main thread"); // The main thread sends the threadHandler message to the subthread after receiving the message. sendMessageDelayed (message, 1000) ;};}; private Handler threadHandler; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); sendButton = (Button) findViewById (R. id. send); sendButton. setOnClickListener (this); // HandlerThread is the thread, where handlerHandlerThread thread = new HandlerThread ("handler stread"); thread. start (); threadHandler = new Handler (thread. getLooper () {@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); Message message = new Message (); // After receiving the Message, the subthread sends the message handler to the main thread. sendMessageDelayed (message, 1000); Log. e ("TAG", "sub-thread") ;};}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. send: handler. sendEmptyMessage (1); break; default: break ;}}}

Log diary main thread sub-thread .....

**************************************** **************

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.