Android Handler Detailed

2010-12-11  来源:本站原创  分类:Mobile  人气:135 

/ ***
* Handler definitions:

* Main accept the child thread to send the data and use this data with the main thread update the UI. When the application starts,

* Android will first open a main thread (UI thread that is), the main thread for the management interface of the UI controls, the event distribution, for example,

* If you click on a Button, Android will be distributed to the Button on the event, to respond to your operation.

* If you need a time-consuming operation at this time, for example: read data network, or read the local time when the larger a file, you can not put these operations on the main thread,

* If you put the main thread, then the interface will appear the phenomenon of suspended animation, if 5 seconds is not yet complete, then Android system will receive an error message "forced to close."

* This time we need to put these time-consuming operation, in a child thread, because the child thread related to UI update, Android main thread is thread safe,

* That is, update the UI can only be updated in the main thread, the child thread in the operation is dangerous. This time, Handler appeared to solve this complex problem,

* The Handler is running in the main thread (UI thread), it is with the sub-thread to pass through the Message object data

* This time, Handler to take in for the child thread pass over the (sub-thread with sedMessage () method returns brother) Message object (which contains data), the main thread of these messages into the queue, with the main thread to update UI.

* Handler features:

* Handler Message objects can be distributed to the main thread and the Runnable object, each Handler instance, he will be bound to create a thread (usually located in the main thread),

* It has two functions: (1): Runnable arrangements in a message or a place in the main thread execution, (2) to arrange an action in a different thread

* Handler carve some of the ways message

* Post (Runnable)

* PostAtTime (Runnable, long)

* PostDelayed (Runnable, long)

* SendEmptyMessage (int)

* SendMessage (Message)

* SendMessageAtTime (Message, long)

* SendMessageDelayed (Message, long)

* The above post class method allows you to arrange a Runnable object to the main thread in the queue, when the need is different from the main UI thread will need to be used with the HandlerThread:

* HandlerThread handlerThread = new HandlerThread ("myHandlerThread");

* HandlerThread.start ();

* Handler = new Handler (handlerThread.getLooper ());* sendMessage class methods, allowing you to arrange a Message object with the data to the queue, wait for the update.

* @ Author xiaoshuang

*

* /

public class HandlerActivity extends Activity {

private TextView textView;

private MyHandler myHandler;

private Button button;

private ProgressBar progressBar;

private MyThread m = new MyThread ();

/ ** Called when the activity is first created. * /

@ Override

public void onCreate (Bundle savedInstanceState) {

super.onCreate (savedInstanceState);

setContentView (R.layout.main);

textView = (TextView) findViewById (R.id.text);

button = (Button) findViewById (R.id.startButton);

progressBar = (ProgressBar) findViewById (R.id.bar);

progressBar.setMax (100);

button.setOnClickListener (new View.OnClickListener () {

@ Override

public void onClick (View arg0) {

myHandler = new MyHandler ();

new Thread (m). start ();

System.out.println ("onCreate - The Thread is:" + Thread.currentThread (). GetId ());

}

});

}

/ / Update in the UI, the implementation of the main UI thread where the thread

class MyHandler extends Handler {/ / inherit the Handler class, you must rewrite handleMessage method

public MyHandler () {

}

public MyHandler (Looper l) {

super (l);

}

@ Override

public void handleMessage (Message msg) {/ / implementation of the notification received, then the order of execution is in accordance with the queue, that is, FIFO

System.out.println ("Handler - The ThreadId is:" + Thread.currentThread (). GetId ());

super.handleMessage (msg);

Bundle b = msg.getData ();

String textStr0 = textView.getText (). ToString ();

String textStr1 = b.getString ("textStr");

HandlerActivity.this.textView.setText (textStr0 + "" + textStr1); / / Change the value of the TextView

int barValue = b.getInt ("barValue"); HandlerActivity.this.progressBar.setProgress (barValue); / / Change the value of progress bar which

}

}

/ / The thread will be run in a separate thread

class MyThread implements Runnable {

int i = 1;

@ Override

public void run () {

while (i <11) {

System.out.println ("Thread - The ThreadId is:" + Thread.currentThread (). GetId ());

try {

Thread.sleep (1000);

} Catch (InterruptedException e) {

e.printStackTrace ();

}

Message msg = new Message ();

Bundle b = new Bundle ();

b.putString ("textStr", "threads to run" + i + "times");

b.putInt ("barValue", i * 10);

i + +;

msg.setData (b);

HandlerActivity.this.myHandler.sendMessage (msg); / / Handler through sendMessage send updates to the UI message

}

}

}

}

/ ***

* Handler definitions:

* Main accept the child thread to send the data and use this data with the main thread update the UI. When the application starts,

* Android will first open a main thread (UI thread that is), the main thread for the management interface of the UI controls, the event distribution, for example,

* If you click on a Button, Android will be distributed to the Button on the event, to respond to your operation.

* If you need a time-consuming operation at this time, for example: read data network, or read the local time when the larger a file, you can not put these operations on the main thread,

* If you put the main thread, then the interface will appear the phenomenon of suspended animation, if 5 seconds is not yet complete, then Android system will receive an error message "forced to close."

* This time we need to put these time-consuming operation, in a child thread, because the child thread related to UI update, Android main thread is thread safe,

* That is, update the UI can only be updated in the main thread, the child thread in the operation is dangerous. This time, Handler appeared to solve this complex problem,

* The Handler is running in the main thread (UI thread), it is with the sub-thread to pass through the Message object data

* This time, Handler to take in for the child thread pass over the (sub-thread with sedMessage () method returns brother) Message object (which contains data), the main thread of these messages into the queue, with the main thread to update UI. * Handler features:

* Handler Message objects can be distributed to the main thread and the Runnable object, each Handler instance, he will be bound to create a thread (usually located in the main thread),

* It has two functions: (1): Runnable arrangements in a message or a place in the main thread execution, (2) to arrange an action in a different thread

* Handler carve some of the ways message

* Post (Runnable)

* PostAtTime (Runnable, long)

* PostDelayed (Runnable, long)

* SendEmptyMessage (int)

* SendMessage (Message)

* SendMessageAtTime (Message, long)

* SendMessageDelayed (Message, long)

* The above post class method allows you to arrange a Runnable object to the main thread in the queue, when the need is different from the main UI thread will need to be used with the HandlerThread:

* HandlerThread handlerThread = new HandlerThread ("myHandlerThread");

* HandlerThread.start ();

* Handler = new Handler (handlerThread.getLooper ());

* SendMessage class methods, allowing you to arrange a Message object with the data to the queue, wait for the update.

* @ Author xiaoshuang

*

* /

public class HandlerActivity extends Activity {

private TextView textView;

private MyHandler myHandler;

private Button button;

private ProgressBar progressBar;

private MyThread m = new MyThread ();

/ ** Called when the activity is first created. * /

@ Override

public void onCreate (Bundle savedInstanceState) {

super.onCreate (savedInstanceState);

setContentView (R.layout.main);

textView = (TextView) findViewById (R.id.text);

button = (Button) findViewById (R.id.startButton);

progressBar = (ProgressBar) findViewById (R.id.bar);

progressBar.setMax (100);

button.setOnClickListener (new View.OnClickListener () {

@ Override

public void onClick (View arg0) {

myHandler = new MyHandler ();

new Thread (m). start ();

System.out.println ("onCreate - The Thread is:" + Thread.currentThread (). GetId ());

}

});

}

/ / Update in the UI, the implementation of the main UI thread where the thread

class MyHandler extends Handler {/ / inherit the Handler class, you must rewrite handleMessage method

public MyHandler () {

}

public MyHandler (Looper l) {

super (l);

}

@ Override

public void handleMessage (Message msg) {/ / implementation of the notification received, then the order of execution is in accordance with the queue, that is, FIFO

System.out.println ("Handler - The ThreadId is:" + Thread.currentThread (). GetId ());

super.handleMessage (msg);

Bundle b = msg.getData ();

String textStr0 = textView.getText (). ToString ();

String textStr1 = b.getString ("textStr");

HandlerActivity.this.textView.setText (textStr0 + "" + textStr1); / / Change the value of the TextView

int barValue = b.getInt ("barValue");

HandlerActivity.this.progressBar.setProgress (barValue); / / Change the value of progress bar which

}

}

/ / The thread will be run in a separate thread

class MyThread implements Runnable {

int i = 1;

@ Override

public void run () {

while (i <11) {

System.out.println ("Thread - The ThreadId is:" + Thread.currentThread (). GetId ());

try {

Thread.sleep (1000);

} Catch (InterruptedException e) {

e.printStackTrace ();

}

Message msg = new Message ();

Bundle b = new Bundle ();

b.putString ("textStr", "threads to run" + i + "times");

b.putInt ("barValue", i * 10);

i + +;

msg.setData (b);

HandlerActivity.this.myHandler.sendMessage (msg); / / Handler through sendMessage send updates to the UI message

}

}

}

}

相关文章
  • Android Handler Detailed 2010-12-11

    / *** * Handler definitions: * Main accept the child thread to send the data and use this data with the main thread update the UI. When the application starts, * Android will first open a main thread (UI thread that is), the main thread for the manag

  • Android Handler use!!! 2010-10-20

    Hello everybody we speak of this section is to use Android Handler, Handler speaking, we first put a small problem is how to make the program about 5 seconds to update the Title. First we look at the people who used to Java programming, the use of th

  • 深入Android Handler与线程间通信ITC的详解 2014-07-21

    本篇文章是对Android的Handler与线程间通信ITC进行了详细的分析介绍,需要的朋友参考下 在<Android Handler之消息循环的深入解析>中谈到了Handler是用于操作线程内部的消息队列,所以Handler可以用来线程间通信ITC,这种方式更加安全和高效,可以大大减少同步的烦恼,甚至都可以不用syncrhonized. 线程间通讯ITC正常情况下函数调用栈都会生存在同一个线程内,想要把执行逻辑交换到其他线程可以新建一个Thread,然后start().另外一种方法就是用IT

  • Android Handler主线程和一般线程通信的应用分析 2014-11-18

    本篇文章小编为大家介绍,Android Handler主线程和一般线程通信的应用分析.需要的朋友参考下 Handler的定义:主要接受子线程发送的数据, 并用此数据配合主线程更新UI. 解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作.如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候

  • Android Handler leak 分析及解决办法 2013-09-12

    In Android, Handler classes should be static or leaks might occur, Messages enqueued on the application thread's MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaki

  • Android Handler 引起内存泄露的解决方案 2014-11-22

    当我们这样写在一个Activity中时,Android Lint会提示我们这样一个 warning: In Android, Handler classes should be static or leaks might occur.. 意思说:在Android中,Handler 类应该是静态的否则可能发生泄漏 同样在Eclipse代码编辑区域的 Handler定义行也会出现类似的警告,一般都会加上supresslint的注解 先来看看,为什么会出现这种问题: 1.当Android程序第一次创建

  • Detailed Android Handler (Reprinted) 2011-05-17

    / *** * Handler definitions: * Main accept the child thread to send the data and use this data with the main thread update the UI . When an application starts, * Android will first open a main thread (UI thread that is), the main thread for the manag

  • Android Handler Summary 2010-07-15

    Reprinted: http://springhi-2009.javaeye.com/blog/698146 <1> Handler's definition: Major sub-thread to send the data received and used this data with the main thread update UI. Explanation: When the application starts, Android will first open a main

  • [Android] handler class analysis 2010-09-05

    [Change] Android in the handler class is its unique tools for managing threads, facilitate the communication between threads. Each application (apk), is a separate process, running on separate instances Dalvik virtual machine, then run on a separate

  • android handler Learning 2010-11-04

    package pos.app; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater;

  • Android handler to use 2010-11-18

    android inside for asynchronous message handling, provides a Handler implementation scheme. There are many appropriate applications Handler and nuances, make it in, and Thread, and when used in conjunction with Service and other to achieve good resul

  • Message, MessageQueue, Looper, Handler Detailed + instance (Reprinted) 2010-12-16

    http://www.eoeandroid.com/viewthread.php?tid=49595&highlight=handler First, several key concepts 1, MessageQueue: is a data structure, see the name of justice to know that a message queue, where the message store. Each thread can have at most a Messa

  • Message, MessageQueue, Looper, Handler Detailed + instance 2011-01-03

    http://www.eoeandroid.com/viewthread.php?tid=49595&highlight=handler First, several key concepts 1, MessageQueue: is a data structure, see the name of justice to know that a message queue, where the message store. Each thread can have at most a Messa

  • android handler multithreading demo (turn) 2011-05-26

    andriod Handler and Looper provided to meet the communication between threads. In order to study the question of which thread mechanism, wrote a two demo: Demo1: package com.mp; import android.app.Activity; import android.os.Bundle; import android.os

  • In Android Handler, Looper, MessageQueue and Thread 2011-10-08

    A few days ago, and colleagues explored the mechanism about the news in Android, explores the process of sending and receiving messages as well as the relationship between threads. Although we often use these basic things, but understanding its inter

  • Android Handler的详细介绍 2013-12-13

    Handler当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发 Handler的定义 主要接受子线程发送的数据, 并用此数据配合主线程更新UI. 解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发. 比如说, 你要是点击一个 Button, Android会分发事件到Button上,来响应你的操作.如果此时需要一个耗时的操作,例如: 联网读取数据,

  • android Handler详细使用方法实例 2014-08-08

    本文主要介绍Android中Handler的简单使用方法,Handler跟多线程,消息队列联系很紧密,在平常的实际程序开发中比较常见.本文分为4个简单的例子来学校handler 开发环境为android4.1. Handler使用例1这个例子是最简单的介绍handler使用的,是将handler绑定到它所建立的线程中. 本次实验完成的功能是:单击Start按钮,程序会开始启动线程,并且线程程序完成后延时1s会继续启动该线程,每次线程的run函数中完成对界面输出nUpdateThread...文字

  • Android --- Handler 多线程通信示例(ProgressBar) 2012-03-21

    1.修改main.xml文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" and

  • Android handler异常处理 2014-04-28

    old: if (Common.iCallNumber != null) { handler.postDelayed(runnable, 1000); } Timer timer=new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub // 结束的时候消除弹出框 System.out.println("上下文对象---->&g

  • android Handler Analysis 2010-11-17

    First need to understand, handler message is to do an asynchronous operation. Asynchronous everyone knows. A more common example is. A worker thread to update the UI thread of the screen, the direct use of View action is not acceptable. This requires