Original:http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-2-of-5/

his is the second part of my series of blog posts on Android non-UI thread-to-UI thread communications. See herefor the start of the series.  As a refresher, this series of posts is about how non-UI threads can communicate back to the UI thread in an Android application in order to update the user interface.  Non-UI threads are not allowed to make updates to the UI.  Trying to do too much work (as defined as not allowing the user to interact with the UI for more than 5 seconds) on the UI thread leads to ANR errors.

THE SIMPLE APP – REVIEW

In my last post, I provided a simple app (called Simple App) that provided two buttons to start/stop a non-UI thread.  The non-UI thread’s job is to simulate long running work was by generating a random number, call the UI to have a TextView widget update the display of the random number, and then sleep for a number of seconds.

In the first of this five part series, I showed you how to use an Activity’s runOnUiThread() method in a non-UI thread to post requests to change the user interface via the UI thread’s event message queue.  In this blog, option #2 is explained – using the post() method of an Android View component to request changes to the UI.

The SimpleApp example code for demonstrating option #2 can be found here(in an Eclipse project ZIP file).

OPTION 2 – USING VIEW’S POST() METHOD

When a non-UI thread has access to a Viewcomponent from the user interface, the non-UI thread can make a call to that View component’s post() method to request a UI change.

Just like when calling on runOnUiThread() of an Activity, calling on the View’s post() communicates the desire to request work be run on the UI thread by publishing a message in the event queue of the UI thread.  When it can, the UI thread picks up the action message in the event queue and performs the UI change.  So the  post() method is a convenience (just as runOnUiThread is) for completing this messaging operation.

Here is the non-UI thread class – DoSomethingThread from the SimpleApp – that generates a random number and then calls on its publishProgress() method to get the random number displayed on the UI using post().

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class DoSomethingThread extends Thread {
 
  private static final String TAG = "DoSomethingThread";
  private static final int DELAY = 5000; // 5 seconds
  private static final int RANDOM_MULTIPLIER = 10;
 
  @Override
  public void run() {
    Log.v(TAG, "doing work in Random Number Thread");
    while (true) {
      int randNum = (int) (Math.random() * RANDOM_MULTIPLIER);
      publishProgress(randNum);
      try {
        Thread.sleep(DELAY);
      } catch (InterruptedException e) {
        Log.v(TAG, "Interrupting and stopping the Random Number Thread");
        return;
      }
    }
  }
 
  private void publishProgress(int randNum) {
    Log.v(TAG, "reporting back from the Random Number Thread");
    final String text = String.format(getString(R.string.service_msg), randNum);
    mainFrag.resultsTextView.post(new Runnable() {
      @Override
      public void run() {
        mainFrag.getResultsTextView().setText(text);
      }
    });
  }
}

Note in line 3 of the publishProgress() method above in the one line of code that changes between Option 1 (using runOnUiThread) and Option 2 here (using post).

CONSIDERATIONS OF OPTION 2 – POST() METHOD

As indicated, the post() method is using the same event message queue under the covers as runOnUiThread().  So in some regards, many of the pro/cons of post() are that of runOnUiThread().  A StackOverflow post (here) provides some detailed insight.

Essentially, in order to use post(), your non-UI thread must have awareness of a View component (from the UI).  This allows the non-UI thread to avoid direct connection to the Activity (which was required with runOnUiThread).  There are times when your non-UI thread may know a View and not an Activity or vice versa.  However, both options might more tightly couple the non-UI thread to the UI side given View components and Activities are UI “stuff.”

Also as with the runOnUiThread() option, this post() method option requires you to create and manage your threads more directly – and thereby have more control of the thread and its communication but also require you to have more experience with Java concurrency/thread APIs and issues.

Unlike the runOnUiThread() method, the post() method does not check whether the current thread is the UI thread.  Therefore the post() method does not cause the Runnable to execute immediately if it is on the UI thread.  Instead, post() always has an event message pushed to the message queue for reaction by the UI thread.

WRAP UP

Stay tuned to this blog site for the next 3 options regarding the Android thread communications.  Again, if you need help on your mobile project or need some mobile training (Android, iOS, other) let Intertech help.  Please contact us.

Read more: http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-2-of-5/#ixzz3MyttDTTp 
Follow us: @IntertechInc on Twitter | Intertech on Facebook

Android Non-UI to UI Thread Communications(Part 2 of 5)的更多相关文章

  1. Android Non-UI to UI Thread Communications(Part 3 of 5)

    Original:http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-3-of-5/ Conti ...

  2. Android子线程更新UI成功

    android子线程更新UI成功 今天在写demo的时候,在子线程中更新UI,发现更新成功,记录一下. protected void onCreate(Bundle savedInstanceStat ...

  3. Android Phonebook编写联系人UI加载及联系人保存流程(一)

    2014-01-06 17:05:11 将百度空间里的东西移过来. 本文适合ROM定制做Phonebook的童鞋看,其他人飘过即可- Phonebook添加/编辑联系人UI加载及保存联系人流程,是一系 ...

  4. 50个Android开发人员必备UI效果源码[转载]

    50个Android开发人员必备UI效果源码[转载] http://blog.csdn.net/qq1059458376/article/details/8145497 Android 仿微信之主页面 ...

  5. 【Android】11.0 UI开发(二)——列表控件ListView的简单实现1

    ************************ 转载请注明出处:https://www.cnblogs.com/xiaofu007/p/10342462.html ***************** ...

  6. 重大发现: windows下C++ UI库 UI神器-SOUI(转载)

    转载:http://www.cnblogs.com/setoutsoft/p/4996870.html 在Windows平台上开发客户端产品是一个非常痛苦的过程,特别是还要用C++的时候.尽管很多语言 ...

  7. 转: windows下C++ UI库 UI神器-SOUI

    转:http://www.cnblogs.com/setoutsoft/p/4996870.html 前言 在Windows平台上开发客户端产品是一个非常痛苦的过程,特别是还要用C++的时候.尽管很多 ...

  8. 小波说雨燕 第三季 构建 swift UI 之 UI组件集-视图集(六)Picker View视图 学习笔记

    想对PickerView进行操作,只能在代码中操作. 下面 ,再添加三个label组件,然后将所有组件配置到代码中(看代码),然后要实现对PickerView的操作,就要实现它的DataSource协 ...

  9. 【译】UI设计基础(UI Design Basics)--导航(Navigation)(六)

    [译]UI设计基础(UI Design Basics)--导航(Navigation)(六)

随机推荐

  1. 如何用nodejs写入mysql 的blob格式的数据

    So, if the array length equals 4, then the size of blob data in mysql DB must be 4 bytes. And it wor ...

  2. Block 块

    代码块本质上是和其他变量类似.不同的是,代码块存储的数据是一个函数体.使用代码块是,你可以像调用其他标准函数一样,传入参数数,并得到返回值. 脱字符(^)是块的语法标记.按照我们熟悉的参数语法规约所定 ...

  3. 20.时钟抖动(jitter)和时钟偏移(skew)的概念?

    jitter:由于晶振本身稳定性,电源以及温度变化等原因造成了时钟频率的变化,就是jitter,指的是时钟周期的变化.指两个时钟周期之间存在的差值,这个误差是在时钟发生器内部产生的,和晶振或者PLL内 ...

  4. Java实现UDP之Echo客户端和服务端

    Java实现UDP之Echo客户端和服务端 代码内容 采用UDP协议编写服务器端代码(端口任意) 编写客户机的代码访问该端口 客户机按行输入 服务器将收到的字符流和接收到的时间输出在服务器consol ...

  5. c# 各种排序算法+找第二大的数+句子单词反转

    冒泡排序 // 冒泡排序 bubble sort public static int[] BubbleSort(int []array) { bool isContinue = true; ; i & ...

  6. Ionic 2 Guide

    Ionic 2 Guide 最近一直没更新博客,业余时间都在翻译Ionic2的文档.之前本来是想写一个入门,后来觉得干脆把官方文档翻译一下算了,因为官方文档就是最好的入门教程.后来越翻译越觉得这个事情 ...

  7. cocos2dx中的场景和使用方法

    1.一个游戏中有且只有一个导演,但是至少有一个场景 2.场景是游戏元素节点数的根节点,也可以理解为该场景下的渲染树的根节点 3.场景是一个容器,包含了该场景下的所有游戏元素,比如层,精灵 4.场景是导 ...

  8. win8.1 cygwin编译java轻量虚拟机avian

    1.背景 昨天在网上看到别人用aauto写本地小程序写的很爽,我觉得如果java的jre能小一点,凭借java庞大的第三方类库写小工具也还算不错的.本人就经常用eclipse+一些commons包写些 ...

  9. Entity Framework走马观花之把握全局

    在深入学习某项技术之前,应该努力形成对此技术的总体印象,并了解其基本原理,本文的目的就在于此. 一.理解EF数据模型 EF本质上是一个ORM框架,它需要把对象映射到底层数据库中的表,为此,它使用了三个 ...

  10. 开发EXTMVC框架前需要了解的基础知识整理

    1.组件选择器 目的:了解如何选择Extjs中的组件,就跟学习jquery时一定会先要学习:$()选择器一样. 常用场景:       1.在controller中的control事件中用到      ...