UI更新及消息处理机制

[b]ps:[/b]最近学习的知识太广而没深入了解,全因工作紧张,要短期内全面了解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:

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.

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();
}


[url=http://www.androidzz.com/2011/09/android-looper-handler-message/]Looper,Handler,Message源码分析[/url]
[url=http://blog.youkuaiyun.com/mylzc/article/details/6736988]更新UI界面一[/url]
[url=http://blog.youkuaiyun.com/mylzc/article/details/6772129]更新UI界面二[/url]

[url=http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html]google官方关于UI更新及线程[/url]

[url=http://blog.youkuaiyun.com/mars2639/article/details/6650876]invalidate()和postInvalidate() 的区别及使用[/url]
[url=http://disanji.net/2010/12/16/android-invalidate/]Android自定义View中界面刷新的方法 nvalidate()和postInvalidate() 的区别及使用[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值