Android线程间通信一

来源:互联网 发布:id软件下载中文版 编辑:程序博客网 时间:2024/06/05 16:36


线程间通信是Android开发经常使用的功能,分为主线程(UI线程)<-->子线程,子线程<-->子线程,这篇文章介绍主线程和子线程间通信。

首先,因为只有主线程才能更新UI,当主线程操作过多耗时操作时,应用UI不能及时更新,系统也会弹出“ANR”界面,所以我们需要使用子线程帮我们完成一些耗时操作,当子线程完成后把结果告诉主线程即可以更新操作了,下面介绍这个步骤。

我们有一个场景,去下载百度图标,下载完成后显示在界面,下载出错显示出错信息;

结果图:


代码:

[java] view plain copy print?
  1. import android.graphics.Bitmap;  
  2. import android.graphics.BitmapFactory;  
  3. import android.os.Bundle;  
  4. import android.os.Handler;  
  5. import android.os.Message;  
  6. import android.support.v7.app.AppCompatActivity;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.ImageView;  
  10. import android.widget.TextView;  
  11.   
  12. import java.io.IOException;  
  13. import java.io.InputStream;  
  14. import java.net.HttpURLConnection;  
  15. import java.net.MalformedURLException;  
  16. import java.net.URL;  
  17.   
  18. public class MainActivity extends AppCompatActivity implements View.OnClickListener {  
  19.     public static final String IMG_PATH = "http://www.baidu.com/img/bd_logo1.png";  
  20.     public static final int IMG_DOWNLOAD_ACTION = 123;  
  21.     public static final int IMG_DOWNLOAD_URL_ERROR = 124;  
  22.     public static final int IMG_DOWNLOAD_IO_ERROR = 125;  
  23.   
  24.     private Button mBtnDownload;  
  25.     private ImageView mImgLogo;  
  26.     private TextView mTvDownload;  
  27.   
  28.     private Handler mHandler = new Handler(){  
  29.         @Override  
  30.         public void handleMessage(Message msg) {  
  31.             switch(msg.what){  
  32.                 case IMG_DOWNLOAD_ACTION:  
  33.                     mTvDownload.setText("下载成功!");  
  34.                     // 设置图片  
  35.                     mImgLogo.setImageBitmap((Bitmap)msg.obj);  
  36.                     break;  
  37.                 case IMG_DOWNLOAD_URL_ERROR:  
  38.                     mTvDownload.setText("URL出错!");  
  39.                     break;  
  40.                 case IMG_DOWNLOAD_IO_ERROR:  
  41.                     mTvDownload.setText("IO异常!");  
  42.                     break;  
  43.             }  
  44.   
  45.         }  
  46.     };  
  47.   
  48.     @Override  
  49.     protected void onCreate(Bundle savedInstanceState) {  
  50.         super.onCreate(savedInstanceState);  
  51.         setContentView(R.layout.activity_main);  
  52.         initUI();  
  53.     }  
  54.   
  55.     private void initUI() {  
  56.         mBtnDownload = (Button) findViewById(R.id.btn_download);  
  57.         mTvDownload = (TextView) findViewById(R.id.tv_download);  
  58.         mImgLogo = (ImageView)findViewById(R.id.img_logo);  
  59.         mBtnDownload.setOnClickListener(this);  
  60.     }  
  61.       
  62.     @Override  
  63.     public void onClick(View v) {  
  64.         switch (v.getId()){  
  65.             case R.id.btn_download:  
  66.                 // 下载动作  
  67.                 download();  
  68.                 break;  
  69.         }  
  70.     }  
  71.   
  72.     private void download() {  
  73.         // 开启子线程加载图片  
  74.         new Thread(new Runnable() {  
  75.             @Override  
  76.             public void run() {  
  77.   
  78.                 InputStream is = null;  
  79.                 try {  
  80.                     URL url = new URL(IMG_PATH);  
  81.                     // 获取网络连接对象  
  82.                     HttpURLConnection con = (HttpURLConnection) url.openConnection();  
  83.                     // 得到网络资源输入流  
  84.                     is = con.getInputStream();  
  85.                     // 利用图片工厂把输入流转换成图片  
  86.                     Bitmap bitmap = BitmapFactory.decodeStream(is);  
  87.                     // 新建消息对象  
  88.                     Message msg = new Message();  
  89.                     // 设置消息动作含义  
  90.                     msg.what = IMG_DOWNLOAD_ACTION;  
  91.                     // 设置需要传送的图片  
  92.                     msg.obj = bitmap;  
  93.                     // 完成下载发送消息  
  94.                     mHandler.sendMessage(msg);  
  95.   
  96.                 } catch (MalformedURLException e) {  
  97.   
  98.                     // 出现URL异常发送给主线程  
  99.                     Message msg = new Message();  
  100.                     msg.what = IMG_DOWNLOAD_URL_ERROR;  
  101.                     // mHandler.sendEmptyMessage(IMG_DOWNLOAD_URL_ERROR);  
  102.                     mHandler.sendMessage(msg);  
  103.   
  104.                 } catch (IOException e) {  
  105.   
  106.                     // 出现IO异常发送给主线程  
  107.                     Message msg = new Message();  
  108.                     msg.what = IMG_DOWNLOAD_IO_ERROR;  
  109.                     mHandler.sendMessage(msg);  
  110.   
  111.                 }finally{  
  112.   
  113.                     // 关闭流  
  114.                     if(is != null){  
  115.                         try {  
  116.                             is.close();  
  117.                         } catch (IOException e) {  
  118.   
  119.                         }  
  120.                     }  
  121.                 }  
  122.   
  123.             }  
  124.         }).start();  
  125.     }  
  126. }  
布局文件:

[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.   
  7.     <TextView  
  8.         android:id="@+id/tv_download"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_centerHorizontal="true"  
  12.         android:layout_marginTop="64dp"  
  13.         android:textSize="16sp"  
  14.         android:text="未下载"  
  15.         />  
  16.     <Button  
  17.         android:id="@+id/btn_download"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="下载百度图标"  
  21.         android:layout_centerHorizontal="true"  
  22.         android:layout_marginTop="16dp"  
  23.         android:layout_below="@+id/tv_download"  
  24.         android:textSize="16sp"  
  25.         />  
  26.   
  27.     <ImageView  
  28.         android:id="@+id/img_logo"  
  29.         android:layout_width="wrap_content"  
  30.         android:layout_height="wrap_content"  
  31.         android:layout_below="@+id/btn_download"  
  32.         android:layout_marginTop="16dp"  
  33.         />  
  34. </RelativeLayout>  
分析:

Android为主线程和子线程间通信提供了Handler类,我们new出该对象默认是可以传消息给主线程,当主线程获得消息后会按照消息的时间先后进行排队处理;

发消息:

[java] view plain copy print?
  1. <span style="white-space:pre">        </span>    // 新建消息对象  
  2.                     Message msg = new Message();  
  3.                     // 设置消息动作含义  
  4.                     msg.what = IMG_DOWNLOAD_ACTION;  
  5.                     // 设置需要传送的图片  
  6.                     msg.obj = bitmap;  
  7.                     // 完成下载发送消息  
  8.                     mHandler.sendMessage(msg);  
收到消息并处理:

[java] view plain copy print?
  1. private Handler mHandler = new Handler(){  
  2.     @Override  
  3.     public void handleMessage(Message msg) {  
  4.         switch(msg.what){  
  5.             case IMG_DOWNLOAD_ACTION:  
  6.                 mTvDownload.setText("下载成功!");  
  7.                 // 设置图片  
  8.                 mImgLogo.setImageBitmap((Bitmap)msg.obj);  
  9.                 break;  
  10.             case IMG_DOWNLOAD_URL_ERROR:  
  11.                 mTvDownload.setText("URL出错!");  
  12.                 break;  
  13.             case IMG_DOWNLOAD_IO_ERROR:  
  14.                 mTvDownload.setText("IO异常!");  
  15.                 break;  
  16.         }  
  17.   
  18.     }  
  19. };  
在子线程中下载图片并发消息:

[java] view plain copy print?
  1. private void download() {  
  2.     // 开启子线程加载图片  
  3.     new Thread(new Runnable() {  
  4.         @Override  
  5.         public void run() {  
  6.   
  7.             InputStream is = null;  
  8.             try {  
  9.                 URL url = new URL(IMG_PATH);  
  10.                 // 获取网络连接对象  
  11.                 HttpURLConnection con = (HttpURLConnection) url.openConnection();  
  12.                 // 得到网络资源输入流  
  13.                 is = con.getInputStream();  
  14.                 // 利用图片工厂把输入流转换成图片  
  15.                 Bitmap bitmap = BitmapFactory.decodeStream(is);  
  16.                 // 新建消息对象  
  17.                 Message msg = new Message();  
  18.                 // 设置消息动作含义  
  19.                 msg.what = IMG_DOWNLOAD_ACTION;  
  20.                 // 设置需要传送的图片  
  21.                 msg.obj = bitmap;  
  22.                 // 完成下载发送消息  
  23.                 mHandler.sendMessage(msg);  
  24.   
  25.             } catch (MalformedURLException e) {  
  26.   
  27.                 // 出现URL异常发送给主线程  
  28.                 Message msg = new Message();  
  29.                 msg.what = IMG_DOWNLOAD_URL_ERROR;  
  30.                 // mHandler.sendEmptyMessage(IMG_DOWNLOAD_URL_ERROR);  
  31.                 mHandler.sendMessage(msg);  
  32.   
  33.             } catch (IOException e) {  
  34.   
  35.                 // 出现IO异常发送给主线程  
  36.                 Message msg = new Message();  
  37.                 msg.what = IMG_DOWNLOAD_IO_ERROR;  
  38.                 mHandler.sendMessage(msg);  
  39.   
  40.             }finally{  
  41.   
  42.                 // 关闭流  
  43.                 if(is != null){  
  44.                     try {  
  45.                         is.close();  
  46.                     } catch (IOException e) {  
  47.   
  48.                     }  
  49.                 }  
  50.             }  
  51.   
  52.         }  
  53.     }).start();  
  54. }  
0 0