Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
Android异步处理二:使用AsyncTask异步更新UI界面
Android异步处理三:Handler+Looper+MessageQueue深入详解
Android异步处理四:AsyncTask的实现原理
概述:每个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 {
-
-
- 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) {
- switch(msg.what) {
- case MSG_SUCCESS:
- mImageView.setImageBitmap((Bitmap) msg.obj);
- 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);
- 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() {
- HttpClient hc = new DefaultHttpClient();
- HttpGet hg = new HttpGet(http://www.linuxidc.com/pic/logo.gif);//获取安科网的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();
-
-
-
-
-
-
-
-
-
-
- }
- };
-
- }
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从网络获取了安科网的LOGO
,并用bitmap对象存储了这个Logo的像素信息。
此时,如果在这个线程的run()方法中调用
- mImageView.setImageBitmap(bm)
会出现:CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views。原因是run()方法是在新开的线程中执行的,我们上面提到不能直接在非ui线程中操作ui元素。