Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行。Android利用Handler来实现UI线程的更新的。

Handler是Android中的消息发送器,其在哪个Activity中创建就属于且紧紧属于该Activity。还可以说其在哪个线程中new的,就是那个线程的Handler。

Handler的定义: 主要接受子线程发送的数据, 并用此数据配合主线程更新UI.

解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。 如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,,如果你放在主线程中的话,界面会出现假死现象,如果5秒钟还没有完成的话,会收到Android系统的一个错误提示 "强制关闭".这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的. 这个时候,Handler就出现了.来解决这个复杂的问题,由于Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。

以上解释原地址:http://txlong-onz.iteye.com/blog/934957

handler API 译文

A Handler allows you to send andprocessMessageandRunnable objects associated with a thread'sMessageQueue.Each Handler instance is associated with a single thread and that thread'smessage queue. When you create a new Handler, it is bound to the thread /message queue of the thread that is creating it -- from that point on, it willdeliver messages and runnables to that message queue and execute them as theycome out of the message queue.

一个Handler允许你去发送和处理一个Message或者是和与一个线程的MessageQueue关联的Runnable对象。每一个Handler的实例都与一个单线程Thread以及该线程的消息队列MessageQueue关联。当你创建一个新的Handler时,它约束于这个创建它的线程或者线程的队列-从这一点看,他会将Message和Runnable发送给消息队列,并在它们从队列中出来时,处理它们。

There are two main uses for a Handler: (1)to schedule messages and runnables to be executed as some point in the future;and (2) to enqueue an action to be performed on a different thread than yourown.

Handler有两种用法:(1)安排Message和Runnable的执行顺序(2)将某一个操作放在另一个线程中执行。

Scheduling messages is accomplished withthepost(Runnable),postAtTime(Runnable,long),postDelayed(Runnable,long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message,long), andsendMessageDelayed(Message,long)methods. Thepostversions allow you to enqueueRunnable objects to be called by the message queue when they are received;thesendMessageversions allow you to enqueue aMessageobjectcontaining a bundle of data that will be processed by the Handler'shandleMessage(Message)method(requiring that you implement a subclass of Handler).

post(Runnable),postAtTime(Runnable,long),postDelayed(Runnable,long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message,long),sendMessageDelayed(Message,long)方法能够完成消息的处理。Post的函数允许你安排由消息队列调用的Runnable对象。Send的函数允许你安排Message对象,该Message对象包含有一个Bundle数据,该Message传递给是一个实现了Handler类的handleMessage(Message)方法。

When posting or sending to a Handler, youcan either allow the item to be processed as soon as the message queue is readyto do so, or specify a delay before it gets processed or absolute time for itto be processed. The latter two allow you to implement timeouts, ticks, andother timing-based behavior.

当你使用posting或者sending的传递消息给一个Handler时,你可以立刻处理这个它,或者指定一个延迟时间或者准确的时间处理。后两者需要你实现timeouts, ticks, and other timing-based behavior.

When a process is created for yourapplication, its main thread is dedicated to running a message queue that takescare of managing the top-level application objects (activities, broadcastreceivers, etc) and any windows they create. You can create your own threads,and communicate back with the main application thread through a Handler. Thisis done by calling the samepostorsendMessagemethods asbefore, but from your new thread. The given Runnable or Message will then bescheduled in the Handler's message queue and processed when appropriate.

当你的应用程序的一个处理被创建,它的主线程会放置到一个管理顶级应用程序对象的消息队列中(包括activities, broadcast receivers, etc)。你可以创建你自己的线程,通过Handler和主线程通信。方法是通过在你的线程中调用post或者sendMessage方法。Runnable和Message会被安排到Handler的消息队列中并在合适的时候处理。

While the constructor of Message is public,the best way to get one of these is to callMessage.obtain()orone of theHandler.obtainMessage()methods,which will pull them from a pool of recycled objects.

虽然Message的构造方法是public的,但是获得Message的最好方法是通过Message.obtain()或者Handler.obtainMessage()中的一种,它们会从循环池中得到Message.


代码:

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"    android:layout_height="fill_parent"    ><Button android:id="@+id/MyButton"android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="启动"/></LinearLayout>


dialogview.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"  android:layout_height="wrap_content">    <TextView     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="handler接受消息,启动本对话框"/></LinearLayout>


Acitvity

package com.zeph.android.myhandler;import android.app.Activity;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.app.ProgressDialog;import android.content.DialogInterface;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class AndroidHandlerActivity extends Activity {private Button mButton;private ProgressDialog mProgressDialog;private MyHandler myHandler;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mButton = (Button) findViewById(R.id.MyButton);myHandler = new MyHandler();mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {mProgressDialog = new ProgressDialog(AndroidHandlerActivity.this);mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);mProgressDialog.setTitle("请等待");mProgressDialog.setMessage("线程等待5秒,调用dismiss()函数和Handler发送msg");mProgressDialog.setIndeterminate(false);mProgressDialog.setCancelable(false);mProgressDialog.show();new Thread(new MyThread(mProgressDialog, myHandler)).start();}});}public void ShowDialog() {Builder builder = new AlertDialog.Builder(AndroidHandlerActivity.this);builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {}});AlertDialog mAlertDialog = builder.create();mAlertDialog.setTitle("进程结束对话框");LayoutInflater factory = getLayoutInflater();View loginDialogView = factory.inflate(R.layout.dialogview, null);mAlertDialog.setView(loginDialogView);mAlertDialog.show();}public class MyHandler extends Handler {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.arg1) {case 0:ShowDialog();break;default:break;}}}public class MyThread implements Runnable {private MyHandler myHandler;private ProgressDialog mProgressDialog;public MyThread(ProgressDialog mProgressDialog, MyHandler myHandler) {this.myHandler = myHandler;this.mProgressDialog = mProgressDialog;}@Overridepublic void run() {try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}mProgressDialog.dismiss();Message msg = new Message();msg.arg1 = 0;myHandler.sendMessage(msg);}}}


更多相关文章

  1. Android(安卓)的进程与线程总结
  2. Android(安卓)结合源码和实例理解消息机制
  3. Android中利用Handler在子线程中更新界面--简单的小球上下跳动案
  4. Android主线程looper是死循环问题
  5. android的Thread、Runnable、Asyntask的区别与联系
  6. Study on Android【六】--消息机制,异步和多线程
  7. [置顶] 我的Android进阶之旅------>Android基于HTTP协议的多线程
  8. 实现Android监控任意控件或按键双击事件方法
  9. Android中后台定时任务实现,即时数据同步问题思考!

随机推荐

  1. Android EventBus二三事
  2. Android编译打包-gradle task 的依赖
  3. Android进度条学习一
  4. Android Activity的生命周期及四种启动模
  5. android截取屏幕图片
  6. Android获取网络图片并显示的方法
  7. Error:Failed to resolve: com.android.s
  8. Android SDK官方下载地址及在线SDK网址
  9. 判断用户使用的是 Android 手机还是平板
  10. android keyboard keycode