Android中子线程和UI线程通信详解

Android中子线程和UI线程通信详解,第1张

概述Android中子线程和UI线程之间通信的详细解释1.在多线程编程这块,我们经常要使用Handler,Thread和Runnable这三个类,那么他们之间的关系你是否弄清楚了呢?下面详解一下。

AndroID中子线程和UI线程之间通信的详细解释

1.在多线程编程这块,我们经常要使用Handler,Thread和Runnable这三个类,那么他们之间的关系你是否弄清楚了呢?下面详解一下。
2.首先在开发AndroID应用时必须遵守单线程模型的原则:
AndroID UI *** 作并不是线程安全的并且这些 *** 作必须在UI线程中执行。
3.Handler:
(1).概念:
Handler是沟通Activity 与Thread/runnable的桥梁。而Handler是运行在主UI线程中的,它与子线程可以通过Message对象来传递数据。
(2).使用:
A:Handler是运行在UI线程中,主要接收子线程发送的数据信息,并用此数据配合主线程更新UI,用来跟UI主线程交互用。比如可以用handler发送一个message,然后在handler的线程中来接收、处理该消息。
B:消息的处理者。通过Handler对象我们可以封装Message对象,然后通过sendMessage(msg)把Message对象添加到MessageQueue中;当MessageQueue循环到该Message时,就会调用该Message对象对应的handler对象的handleMessage()方法对其进行处理。
C:Handler可以分发Runnable对象,也可以分发Message对象。

4.Message:
 消息对象,顾名思义就是记录消息信息的类。也就是说是信息的载体,存放信息内容。这个类有几个比较重要的字段:

  (1).arg1和arg2:我们可以使用两个字段用来存放我们需要传递的整型值,在Service中,我们可以用来存放Service的ID。
  (2).obj:该字段是Object类型,我们可以让该字段传递某个对象到消息的接受者中。
  (3).what:这个字段可以说是消息的标志,判断是接收了哪个消息。在消息处理中,我们可以根据这个字段的不同的值进行不同的处理,类似于我们在处理button事件时,通过switch(v.getID())判断是点击了哪个按钮。
AndroID推荐通过Message.obtain()或者Handler.obtainMessage()获取Message对象。这并不一定是直接创建一个新的实例,而是先从消息池中看有没有可用的Message实例,存在则直接取出并返回这个实例。反之如果消息池中没有可用的Message实例,则根据给定的参数new一个新Message对象。通过分析源码可得知,AndroID系统默认情况下在消息池中实例化10个Message对象。
5.源码展示:
(1).activity_main.xml布局文件:

<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  xmlns:tools="http://schemas.androID.com/tools"  androID:ID="@+ID/container"  androID:layout_wIDth="match_parent"  androID:layout_height="match_parent"  androID:orIEntation="vertical" >  <button    androID:ID="@+ID/btn"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="自定义Thread继承Thread" />  <button    androID:ID="@+ID/btn2"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="自定义Runnable实现Runnable" />  <button    androID:ID="@+ID/btn3"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="定时更新UI界面,Handler分发Runnable对象" />  <button    androID:ID="@+ID/btn4"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="定时更新UI界面,Handler分发Message对象" />  <TextVIEw    androID:ID="@+ID/tv"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="0" /></linearLayout>

(2).MainActivity.java

package com.chengdong.su.threaddemo;import com.chengdong.su.threaddemo.util.MyRunnable;import com.chengdong.su.threaddemo.util.MyThread;import androID.R.integer;import androID.app.Activity;import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.util.Log;import androID.vIEw.VIEw;import androID.vIEw.VIEw.OnClickListener;import androID.Widget.button;import androID.Widget.TextVIEw;public class MainActivity extends Activity implements OnClickListener {  /** TAG */  private final String TAG = getClass().getSimplename();  /** the object of the button */  private button mbutton;  /** the object of the button */  private button mbutton2;  /** the object of the button */  private button mbutton3;  /** the object of the button */  private button mbutton4;  /** the object of the TextVIEw */  private TextVIEw mTextVIEw;  /** 计数 */  private int mCount = 0;  /** 标志 */  private int MESSAGE_FLAG = 1;  /**   * Handler分发Runnable对象的方式   */  private Handler mHandler = new Handler();  Runnable runnable = new Runnable() {    @OverrIDe    public voID run() {      mCount++;      mHandler.postDelayed(runnable,1000);      mTextVIEw.setText(mCount + "");    }  };  /***   * Handler分发Message对象的方式   */  Handler mHandler2 = new Handler() {    public voID handleMessage(androID.os.Message msg) {      if (msg.what == 1) {        mTextVIEw.setText("Handler分发Message对象的方式");      }    }  };  @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    initVIEw();  }  /**   * 初始化组件对象   */  private voID initVIEw() {    mbutton = (button) findVIEwByID(R.ID.btn);    mbutton2 = (button) findVIEwByID(R.ID.btn2);    mbutton3 = (button) findVIEwByID(R.ID.btn3);    mbutton4 = (button) findVIEwByID(R.ID.btn4);    mbutton.setonClickListener(this);    mbutton2.setonClickListener(this);    mbutton3.setonClickListener(this);    mbutton4.setonClickListener(this);    mTextVIEw = (TextVIEw) findVIEwByID(R.ID.tv);  }  @OverrIDe  public voID onClick(VIEw v) {    switch (v.getID()) {    case R.ID.btn: {      // 方法一:继承的方式:自定义Thread继承Thread,开启一个新的线程      new MyThread().start();      break;    }    case R.ID.btn2: {      // 方法二:实现的方式:implement Runnable      new Thread(new MyRunnable()).start();      break;    }    // 方法三:handler分发Runnable对象:定时更新UI界面 提交计划任务马上执行    case R.ID.btn3: {      // Handler分发Runnable对象      mHandler.post(runnable);      break;    }    // 方法四:Handler分发Message对象 ,定时更新UI界面 提交计划任务马上执行    case R.ID.btn4: {      // 不推荐这种方式      // Message msg = new Message();      // 推荐使用这种获取对象的方式:从消息池中获得可用的Message对象      Message msg = Message.obtain();      msg.what = MESSAGE_FLAG;      mHandler2.sendMessage(msg);      break;    }    default:      break;    }  }}

(3).MyRunnable.java

package com.chengdong.su.threaddemo.util;import androID.util.Log;/*** * 自定义一个MyRunnable线程 *  * @author scd *  */public class MyRunnable implements Runnable {  public MyRunnable() {    super();  }  /** TAG */  private final String TAG = getClass().getSimplename();  @OverrIDe  public voID run() {    for (int i = 0; i < 20; i++) {      Log.e(TAG,Thread.currentThread().getname() + ",实现的方法" + i);    }  }}

(4)MyThread.java

package com.chengdong.su.threaddemo.util;import androID.util.Log;/*** * 自定义一个线程 *  * @author scd *  */public class MyThread extends Thread {  public MyThread() {    super();  }  /** TAG */  private final String TAG = getClass().getSimplename();  @OverrIDe  public voID run() {    super.run();    for (int i = 0; i < 10; i++) {      Log.e(TAG,继承Thread类:" + i);    }  }}

总结

以上是内存溢出为你收集整理的Android中子线程和UI线程通信详解全部内容,希望文章能够帮你解决Android中子线程和UI线程通信详解所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1142322.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存