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/
Continuing my series on Android non-UI thread-to-UI thread communications, this post covers use of the Handler Framework to facilitate the communications. See here for Part 1 and Part 2 of the series.
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. In the first two posts, I showed how to use an activity’s runOnUiThread() method and a view component’s post() method to have the non-UI thread send a request through the underlying UI event message channel to the UI thread to execute a UI update.
ANDROID’S HANDLER FRAMEWORK
Android threads, in particular the UI thread, have a message queue. Messages in the queue are processed by the thread in order of arrival. In the case of the UI thread, user events (like a button push) cause event messages to be placed in the queue. As explained in the previous posts, the runOnUiThread() and post() methods use this queue under the covers. However, you can use the message queue more directly.
Using the Handler Framework, you can create a message directly and put the message on the UI thread’s queue from the non-UI thread. The framework also lets you build a message handler to listen for the message on the UI thread. Thus, the Handler Framework can provide another means for the non-UI thread to communicate with the UI via the framework pieces.
THE SIMPLEAPP REVIEW
As with the last post, I provide the simple application (called Simple App) to demonstrate the use of the Handler Framework for thread communications. The app has two buttons to start/stop a non-UI thread. The non-UI thread’s job is to simulate long running work 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.

Now let’s see how the Handler Framework can be used in this app to update the UI (the TextView) from the non-UI thread.
OPTION 3 – USING THE HANDLER FRAMEWORK
First, create a Handler in the UI thread to receive and react to new messages sent by the non-UI thread. Here are the steps to create the Handler:
1. Create class that extends android.os.Handler. For simplicity, I created the Handler subclass (called HandlerExtension here) as an inner class to the application’s activity.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
private static class HandlerExtension extends Handler {
private final WeakReference<ShowSomethingActivity> currentActivity;
public HandlerExtension(ShowSomethingActivity activity){
currentActivity = new WeakReference<ShowSomethingActivity>(activity);
}
@Override
public void handleMessage(Message message){
ShowSomethingActivity activity = currentActivity.get();
if (activity!= null){
activity.updateResults(message.getData().getString("result"));
}
}
}
|
The code here may look a little complex due to the static nature and WeakReference in the subclass. If you try to create a simple class that extends Handler, you will find Eclipse and the SDK issues a compiler warning that the Handler class should be static or leaks might occur.

The issue is well explained in a StackOverflow post. While the code may be a little more complex, the post provides a great template example for creating the Handler subclass without memory leaks.
2. Next, add a property to hold the Handler subclass instance in the Activity.
|
1
|
Handler resultHandler;
|
3. Then, from the activity’s onCreate() method, create an instance of the Handler so that it can start processing any incoming messages from the non-UI thread.
|
1
|
resultHandler = new HandlerExtension(this);
|
Second, with the Handler subclass code in place, you can create a message from the non-UI thread and publish it into the UI thread’s message queue using the Handler subclass. Simply create an instance of Messageand add data to the message to indicate to the Handler what UI changes should occur (in this case, providing the random number that needs to be displayed in the TextView widget).
|
1
2
3
4
5
6
7
8
9
|
private void publishProgress(int randNum) {
Log.v(TAG, "reporting back from the Random Number Thread");
String text = String.format(getString(R.string.service_msg),randNum);
Bundle msgBundle = new Bundle();
msgBundle.putString("result", text);
Message msg = new Message();
msg.setData(msgBundle);
resultHandler.sendMessage(msg);
}
|
The SimpleApp example code for demonstrating option #3 can be found here(in an Eclipse project ZIP file).
CONSIDERATIONS OF OPTION 3 – HANDLER FRAMEWORK
The runOnUiThread() and post() methods examined in previous posts are really special Hander Framework conveniences. They use the event queue on the UI thread to perform their task. So why use the Handler Framework directly as shown here? Using the Handler Framework directly is a bit more complex, but it allows you more control. This is a generic framework for thread communication – any thread. It also allows the non-UI thread to communicate without direct knowledge/ties to the activity or UI side components. The non-UI merely has to post a message to a handler.
WRAP UP
In the final two upcoming posts of this series you will see different Android infrastructure to perform the non-UI to UI thread communications – namely the use of Broadcast Receivers and AsyncTask. Stay tune for those posts. If you are looking for some Android training or consulting help, look no further than the sponsor of this blog site: Intertech.
Read more: http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-3-of-5/#ixzz3MyuAnUgJ
Follow us: @IntertechInc on Twitter | Intertech on Facebook
Android Non-UI to UI Thread Communications(Part 3 of 5)的更多相关文章
- Android Non-UI to UI Thread Communications(Part 2 of 5)
Original:http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-2-of-5/ his i ...
- Android子线程更新UI成功
android子线程更新UI成功 今天在写demo的时候,在子线程中更新UI,发现更新成功,记录一下. protected void onCreate(Bundle savedInstanceStat ...
- Android Phonebook编写联系人UI加载及联系人保存流程(一)
2014-01-06 17:05:11 将百度空间里的东西移过来. 本文适合ROM定制做Phonebook的童鞋看,其他人飘过即可- Phonebook添加/编辑联系人UI加载及保存联系人流程,是一系 ...
- 50个Android开发人员必备UI效果源码[转载]
50个Android开发人员必备UI效果源码[转载] http://blog.csdn.net/qq1059458376/article/details/8145497 Android 仿微信之主页面 ...
- 【Android】11.0 UI开发(二)——列表控件ListView的简单实现1
************************ 转载请注明出处:https://www.cnblogs.com/xiaofu007/p/10342462.html ***************** ...
- 重大发现: windows下C++ UI库 UI神器-SOUI(转载)
转载:http://www.cnblogs.com/setoutsoft/p/4996870.html 在Windows平台上开发客户端产品是一个非常痛苦的过程,特别是还要用C++的时候.尽管很多语言 ...
- 转: windows下C++ UI库 UI神器-SOUI
转:http://www.cnblogs.com/setoutsoft/p/4996870.html 前言 在Windows平台上开发客户端产品是一个非常痛苦的过程,特别是还要用C++的时候.尽管很多 ...
- 小波说雨燕 第三季 构建 swift UI 之 UI组件集-视图集(六)Picker View视图 学习笔记
想对PickerView进行操作,只能在代码中操作. 下面 ,再添加三个label组件,然后将所有组件配置到代码中(看代码),然后要实现对PickerView的操作,就要实现它的DataSource协 ...
- 【译】UI设计基础(UI Design Basics)--导航(Navigation)(六)
[译]UI设计基础(UI Design Basics)--导航(Navigation)(六)
随机推荐
- linux安装R语言
系统:centos 6.4 64bit 安装可以使用rpm包安装,也可以用源码安装. 但是rpm安装,各种依赖比较麻烦.所以我采用源码安装. 下载:http://www.r-project.org/ ...
- Object C学习笔记2-NSLog 格式化输出数据
1 . 几种常用类型变量声明 int i =10; BOOL isShow=YES; BOOL isShow=1; float f = 3.1415926; char a =120; NSString ...
- 跨域访问-需要设置HTTP响应标头设置
跨域访问-需要设置HTTP响应标头设置 前提:服务端网站的配置(被请求的网站) 1.需要在IIS服务器站点的功能视图中设置HTTP响应标头: 2.双击“HTTP响应标头”进入设置界面 3.点击右侧添加 ...
- shell 编程基础
1 创建shell脚本文件 要创建一个shell脚本文件,必须在第一行指定要使用的shell,其格式为: #! /bin/bash 接着加上该shell文件的注释,说明该脚本文件用来干什么,有谁创建, ...
- FTP上传文件夹
文件上传类 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; usi ...
- 009--VS2013 C++ 显示位图部分透明化
其实这个更简单,只是把上一编文章的半透明化的代码去掉就可以啦 还是原来那张图片: //全局变量HBITMAP bg, girl;HDC mdc;//起始坐标const int xstart = 50; ...
- [工具]IL Mapper2(C# -> IL 转换器)
下载地址:IL_Mapper2_exe.zip 源文件:IL_Mapper2_src.zip 简介 此工具可以直接把C#代码转换成IL代码查看,省去编译和手动操作ildsam的繁琐.希望能对想研究IL ...
- 零基础学习Linux(二)网页乱码问题
上次的博文零基础学习Linux(一)环境搭建中我们已经将Linux环境搭建完毕了,接下来我们就可以进行相关的操作了,在进行操作之前,我们先来看一下大家可能遇到的中文网页乱码问题. 1.问题演示 a)输 ...
- 解决SQLite数据库中文乱码问题
关于SQLite中出现中文乱码的分析以及解决方案 我们在使用SQLite数据库时候,可能会发现,向数据库插入数据时候显示的是汉字,但通过SQLite读出来时却显示的乱码,这是因为SQLite数据库 ...
- JAVA类与对象(五)----对象的生成、使用
对象的生成 创建一个对象包括对象的声明.实例化.初始化三部分. 1.声明-----类名对象名 声明并不是为对象分配内存空间,而只是分配一个引用空间.对象的引用类似于指针,是32位的地址空间,它的值指向 ...