Android异步处理系列文章四篇之一使用Thread+Handler实现非UI线程更新UI界面
目录:
Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
Android异步处理二:使用AsyncTask异步更新UI界面
Android异步处理三:Handler+Looper+MessageQueue深入详解
Android异步处理四:AsyncTask的实现原理
Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
概述:每个Android应用程序都运行在一个dalvik虚拟机进程中,进程开始的时候会启动一个主线程(MainThread),主线程负责处理和ui相关的事件,因此主线程通常又叫UI线程。而由于Android采用UI单线程模型,所以只能在主线程中对UI元素进行操作。如果在非UI线程直接对UI进行了操作,则会报错:
CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views
。
Android为我们提供了消息循环的机制,我们可以利用这个机制来实现线程间的通信。那么,我们就可以在非UI线程发送消息到UI线程,最终让Ui线程来进行ui的操作。
对于运算量较大的操作和IO操作,我们需要新开线程来处理这些繁重的工作,以免阻塞ui线程。
例子:下面我们以获取CSDN logo的例子,演示如何使用Thread+Handler的方式实现在非UI线程发送消息通知UI线程更新界面。
ThradHandlerActivity.java:
public class ThreadHandlerActivity extends Activity {
/** Called when the activity is first created. */ private static final int MSG_SUCCESS = 0;//获取图片成功的标识
private static final int MSG_FAILURE = 1;//获取图片失败的标识 private ImageView mImageView;
private Button mButton; private Thread mThread; private Handler mHandler = new Handler() {
public void handleMessage (Message msg) {//此方法在ui线程运行
switch(msg.what) {
case MSG_SUCCESS:
mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();
break; case MSG_FAILURE:
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();
break;
}
}
}; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView= (ImageView) findViewById(R.id.imageView);//显示图片的ImageView
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
if(mThread == null) {
mThread = new Thread(runnable);
mThread.start();//线程启动
}
else {
Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();
}
}
});
} Runnable runnable = new Runnable() { @Override
public void run() {//run()在新的线程中运行
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo
final Bitmap bm;
try {
HttpResponse hr = hc.execute(hg);
bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
} catch (Exception e) {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败
return;
}
mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象 // mImageView.setImageBitmap(bm); //出错!不能在非ui线程操作ui元素 // mImageView.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。
//
// @Override
// public void run() {//run()方法会在ui线程执行
// mImageView.setImageBitmap(bm);
// }
// });
}
}; }
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/button" android:text="@string/button_name" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ImageView android:id="@+id/imageView" android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
strings.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/button" android:text="@string/button_name" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ImageView android:id="@+id/imageView" android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zhuozhuo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission><!--不要忘记设置网络访问权限--> <application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ThreadHandlerActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> </application>
</manifest>
运行结果:
为了不阻塞ui线程,我们使用mThread从网络获取了CSDN的LOGO
,并用bitmap对象存储了这个Logo的像素信息。
此时,如果在这个线程的run()方法中调用
mImageView.setImageBitmap(bm)
会出现:CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views。原因是run()方法是在新开的线程中执行的,我们上面提到不能直接在非ui线程中操作ui元素。
非UI线程发送消息到UI线程分为两个步骤
一、发送消息到UI线程的消息队列
通过使用Handler的
Message obtainMessage(int what,Object object)
构造一个Message对象,这个对象存储了是否成功获取图片的标识what和bitmap对象,然后通过message.sendToTarget()方法把这条message放到消息队列中去。
二、处理发送到UI线程的消息
在ui线程中,我们覆盖了handler的
public void handleMessage (Message msg)
这个方法是处理分发给ui线程的消息,判断msg.what的值可以知道mThread是否成功获取图片,如果图片成功获取,那么可以通过msg.obj获取到这个对象。
最后,我们通过
mImageView.setImageBitmap((Bitmap) msg.obj);
设置ImageView的bitmap对象,完成UI的更新。
补充:
事实上,我们还可以调用
View的post方法来更新ui
mImageView.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。 @Override
public void run() {//run()方法会在ui线程执行
mImageView.setImageBitmap(bm);
}
});
这种方法会把Runnable对象发送到消息队列,ui线程接收到消息后会执行这个runnable对象。
从例子中我们可以看到handler既有发送消息和处理消息的作用,会误以为handler实现了消息循环和消息分发,其实Android为了让我们的代码看起来更加简洁,与UI线程的交互只需要使用在UI线程创建的handler对象就可以了。
转自:http://blog.csdn.net/mylzc/article/details/6777767
Android异步处理系列文章四篇之一使用Thread+Handler实现非UI线程更新UI界面的更多相关文章
- Android异步处理系列文章四篇之三
Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面Android异步处理二:使用AsyncTask异步更新UI界面Android异步处理三:Handler+Loope ...
- Android异步处理系列文章四篇之四 AsyncTask的实现原理
Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面Android异步处理二:使用AsyncTask异步更新UI界面Android异步处理三:Handler+Loope ...
- Android异步处理系列文章四篇之二 使用AsyncTask异步更新UI界面
Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面Android异步处理二:使用AsyncTask异步更新UI界面Android异步处理三:Handler+Loope ...
- 【转载】Android异步处理系列文章
本博文地址:http://blog.csdn.net/mylzc/article/details/6777767 转载请注明出处. 为了给用户带来良好的交互体验,在Android应用的开发过程中需要把 ...
- Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
Android应用的开发过程中需要把繁重的任务(IO,网络连接等)放到其他线程中异步执行,达到不阻塞UI的效果. 下面将由浅入深介绍Android进行异步处理的实现方法和系统底层的实现原理. 本文介绍 ...
- android 在非UI线程更新UI仍然成功原因深入剖析
”只能在UI主线程中更新View“. 这句话很熟悉吧? 来来,哥们,看一下下面的例子 @Override protected void onCreate(Bundle savedInsta ...
- 【android异步处理】一个关于android异步处理的文章系列
最近读了Android异步处理系列文章索引,感觉这个文章系列写得不错!可以作为参考
- Android子线程更新UI的方法总结
版权声明:本文为博主原创文章,转载请注明出处:https://i.cnblogs.com/EditPosts.aspx?postid=6121280 消息机制,对于Android开发者来说,应该是非常 ...
- 安卓 异步线程更新Ui
异步跟新UI: 1.handler+Thread(runnable):如果handler和Thread都写在了一个Java文件中,就不说了,如果runnable定义在了一个单独的类文件中,可以通过在构 ...
随机推荐
- mysql week 的使用方法
mysql week 的使用方法,详情请看: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function ...
- Content-type详解
HttpHeader里的Content-Type 之前一直分不清楚post请求里Content-Type方式,如application/x-www-form-urlencoded.multipart/ ...
- window 7喇叭有红叉,耳机扬声器已拔出驱动无法修复
win7系统没声音前提是声卡驱动已经安装完全,且没有问题.Windows 7系统电脑有耳机的存在,但是还是显示扬声器耳机或耳机已拔出 ,未修复故障,首先可以百度下看下其他教程,尝试过还是不行的时候,可 ...
- 预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反)(转)
用VC++ 2008 编写C语言程序,编译出现错误: 预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反) 解决方法: 建工程时 建立空项目 或者在项目设置里关闭预编 ...
- normalize.css的使用
normalize.css有下面这几个目的: 保护有用的浏览器默认样式而不是完全去掉它们一般化的样式:为大部分HTML元素提供修复浏览器自身的bug并保证各浏览器的一致性优化CSS可用性:用一些小技巧 ...
- 【GPU编解码】GPU硬编码 (转)
一.OpenCV中的硬编码 OpenCV2.4.6中,已实现利用GPU进行写视频,编码过程由cv::gpu::VideoWriter_GPU完成,其示例程序如下. 1 int main(int arg ...
- linux远程开启不挂起的服务
解决Linux关闭终端(关闭SSH等)后运行的程序自动停止 λ nohup --help Usage: nohup COMMAND [ARG]... or: nohup OPTION Run COMM ...
- React 中 keys 的作用是什么?
Keys 是 React 用于追踪哪些列表中元素被修改.被添加或者被移除的辅助标识. render () { return ( <ul> {this.state.todoItems.map ...
- 创建py模板
创建模板之后,每次新建py文件,已初始定义的代码段将会自动出现在py文件中.
- 使用zlib库进行目录打包
代码很简单,具体过程就不写了. 关于加密压缩,可以看http://www.zlib.net/zlib_faq.html#faq38 中的描述,说是不支持的,但是创建的时候可以传入密码进去,不过我还没有 ...