---
title: "UI更新及消息处理机制"
author: "喧嚣求静"
date: "2011-12-08T08:24:26Z"
tags: []
categories: ["移动开发"]
slug: "ui"
draft: false
lastmod: "2011-12-08T08:48:15Z"
id: 1297292
url: "https://913.iteye.com/blog/1297292"
---

**ps:**最近学习的知识太广而没深入了解，全因工作紧张，要短期内全面了解android，没办法只有走马观花，一睹android全貌。由于只是一扫而过，心中只留下概念，没有明白原理，故用到时又得google，特花精力和时间，所以自己决定，把学习过程中点滴全记录在博客上，方便自己用时查找，同时也方便感兴趣的朋友学习。
the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

    Do not block the UI thread
    Do not access the Android UI toolkit from outside the UI thread 

For example, below is some code for a click listener that downloads an image from a separate thread and displays it in an ImageView:

```java

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
            mImageView.setImageBitmap(b);
        }
    }).start();
}

```

To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

    1.Activity.runOnUiThread(Runnable)
    2.View.post(Runnable)
    3.View.postDelayed(Runnable, long)
    4.Using AsyncTask
    5.android.view.View.postInvalidate()
       Cause an invalidate to happen on a subsequent cycle through the event loop.

```java

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}

```


[Looper，Handler，Message源码分析](http://www.androidzz.com/2011/09/android-looper-handler-message/)
[更新UI界面一](http://blog.csdn.net/mylzc/article/details/6736988)
[更新UI界面二](http://blog.csdn.net/mylzc/article/details/6772129)

[google官方关于UI更新及线程](http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html)

[invalidate()和postInvalidate() 的区别及使用](http://blog.csdn.net/mars2639/article/details/6650876)
[Android自定义View中界面刷新的方法 nvalidate()和postInvalidate() 的区别及使用](http://disanji.net/2010/12/16/android-invalidate/)