android-non-ui-to-ui-thread-communications-part-4-of-5
In parts 1-3 of this series, I have explored three different means for an Android non-UI thread to communicate user interface updates to the UI thread. The links below are to the series posts.
In this fourth installment, I want to show you how to use a broadcasts and a broadcast receiver to provide non-UI to UI thread communications.
BACKGROUND NON-UI THREAD TO UI THREAD COMMS
As background for those jumping into the middle of this series, non user interface (UI) threads are not allowed to make updates to the UI. For example, using a non-UI thread to update a TextView’s displayed text results in a CalledFromWrongThreadException. However, 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 Android Not Responsive errors. So you need to have non-UI threads perform larger/bigger computing tasks, but need those threads to be able to communicate updates back to the UI thread to perform display updates.
In the first three posts, I showed how to use an activity’s runOnUiThread() method, a view component’s post() method, and the Android Handler Framework to have the non-UI thread send a user interface update request back to the UI thread for display. Each of these past three options take advantage of the underlying UI event message channel to message the UI thread to perform the user interface update. In this post, I show you a different means of providing the communications via broadcast intent that is acted on by a BroadcastReceiver on the UI thread.
SIMPLE APP
A simple application (called Simple App) will again be used to demonstrate the use of broadcast messages 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.
The application code for this simple example is provided here.
OPTION 4 – USING A BROADCAST
Broadcasts are Android Intents that indicate some action has occurred. Some broadcasts are system broadcasts. For example, one of the built in Android broadcast is that the battery is low. You can create your own custom broadcasts as well.
Broadcast receivers are components in the application that listen for broadcasts and take some action. You could, for example, build a broadcast receiver to listen for the battery getting low broadcast event in order to inform the user that unsaved data should be saved quickly. Of course, you can also build a broadcast receiver to listen for your own custom application broadcasts.

So, a broadcast and broadcast receiver can be used to accomplish the non-UI to UI thread communications. The non-UI thread can publish a broadcast intent that a broadcast receiver associated to the UI thread uses to perform the UI update.
Now, per the Android documentation on BroadcastReceivers, if your custom application broadcasts are not going to be used across applications, you should consider using a LocalBroadcastManager to send a local broadcast versus a system broadcast. A LocalBroadcastManager’s intent broadcasts are not broadcast to other applications. They are therefore a bit more efficient and secure than using a general broadcast message. You can read a prior blog postof mine to learn more about LocalBroadcastManager and local broadcasts.

Therefore, given the fact that the non-UI to UI thread communication is local to your application, I would recommend (and will show below) using the LocalBroadcastManager to perform the thread communications.
PUBLISHING THE BROADCAST
First, from the non-UI thread, create an Intent that provides the necessary information to the UI thread about the user interface updates that are required. In this example, the non-UI thread simply provides the new random number that was generated as extra data (under the key of “result”) in the Intent. Then use an instance of Android’s LocalBroadcastManager to send the local broadcast.
|
1
2
3
|
Intent intent = new Intent("com.intertech.random.generation");
intent.putExtra("result", text);
LocalBroadcastManager.getInstance(ShowSomethingActivity.this).sendBroadcast(intent);
|
SET A BROADCAST RECEIVER LISTENING
On the UI thread, you need to create an instance of BroadcastReceiver to listen for updates coming from the non-UI thread. In this simple application, I created an anonymous BroadcastReceiver instance from within the createBroadcastRecevier() method which is called from the onCreate( ) method of the application’s main activity.
|
1
2
3
4
5
6
7
8
|
private BroadcastReceiver createBroadcastReceiver() {
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateResults(intent.getStringExtra("result"));
}
};
}
|
The updateResults() method of the broadcast receiver gets the TextView and updates the string with what is in the broadcast’s extra data at “result”.
Once the broadcast receiver is created in onCreate(), use a LocalBroadcastManager to register the UI thread for the broadcasts sent by the non-UI thread, specifically those with the string action of “com.intertech.random.generation”);
|
1
2
3
4
5
6
7
8
9
|
@Override
protected void onCreate(Bundle savedInstanceState) {
...
resultReceiver = createBroadcastReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(resultReceiver, new IntentFilter("com.intertech.random.generation"));
...
}
|
Now, once the non-UI thread publishes its local broadcast, the broadcast receiver listening for the message gets the Intent and takes on the responsibility of updating the UI on the UI thread.
As a last bit of housekeeping, make sure to unregister the broadcast receiver when the communication between non-UI and UI threads is no longer needed. In this example, I unregister the BroadcastReceiver in the onDestroy() method of the main activity.
|
1
2
3
4
5
6
7
|
@Override
protected void onDestroy() {
if (resultReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(resultReceiver);
}
super.onDestroy();
}
|
CONSIDERATIONS OF OPTION 4 – BROADCASTS
The broadcast option is not reliant on the message event queue. Instead it relies on a different Android set of components; namely the Intent and Intent listener called a broadcast receiver. This sub-framework has pluses and minuses. There are no convenience methods as provided through methods like post() and runOnUiThread() using the thread’s event queue. Some consider working with Intents, BroadcastReceivers (and LocalBroadcastManager) a bit more complex. However, the broadcast intent can conveniently carry quite a bit of data to the UI thread from the non-UI thread. Also importantly, the non-UI thread and UI thread do not have to share any component knowledge. So the non-UI thread is quite decoupled from the UI thread. The only information shared by the two threads is the name of the intent action.
WRAP UP
Just one more post in this series. In that post, I’ll show you how to use an AsyncTask’s for do long running work on a separate non-UI thread, while still being able to push changes to the UI via special UI thread methods.
Please connect with Intertechif you or your organization could use help on your Android/mobile project.
Read more: http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-4-of-5/#ixzz3Myuoh9Jf
Follow us: @IntertechInc on Twitter | Intertech on Facebook
android-non-ui-to-ui-thread-communications-part-4-of-5的更多相关文章
- 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 ...
- 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)(六)
随机推荐
- java intellij 写控制台程序 窗口程序
建一个空项目,建一个main函数 用application,就可以运行了 /** * Created by robin on 15/10/11. */public class hello { pu ...
- 时隔3年半Spring.NET 2.0终于正式Release了
一直很喜欢Spring.NET,不过2011年8月2日1.3.2正式release之后,再没有正式版本的release了. 直到4天前,Spring.NET 2.0 GA终于Release. http ...
- Linux C 文件与目录2 文件的打开与关闭
文件的打开与关闭 open和close 文件的打开指的是从磁盘中找到一个文件,返回一个整形的打开文件顺序的编号.打开的文件处于可读.可写状态.文件的关闭指的是释放打开的文件,是文件处于不可读写的状态. ...
- [shell基础]——数组
数组赋值 1. 逐个数组元素赋值 # array[0]=11 # array[1]=22 # array[2]=33 # echo ${array[@]} 11 22 33 33 2. array( ...
- C++设计模式——享元模式
本文版权归果冻说所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.如果这篇文章对你有帮助,你可以请我喝杯咖啡. » 本文链接:http:// ...
- 程序调试手段之gdb, vxworks shell
调试一个程序主要用到的功能: 启动程序 设置函数断点 设置数据断点 单步执行 查看内存值 修改内存值 linux下的gdb,和vxworks下的shell 虽然使用方式和调试命令略有不同,但是都能满足 ...
- (转载)HTML:模拟链接被按下,在新标签页打开页面,不使用window.open(可能被拦截)
原文: http://www.cppblog.com/biao/archive/2010/08/21/124196.html 当按下一个按钮时,想打开一个新的标签页,可以使用window.open去实 ...
- mysql存储过程和游标以及if-else,while典型实例
-- -------------------------------------------------------------------------------- -- Routine DDL - ...
- sql数据库的表连接方式图文详解
sql数据库表连接,主要分为:内连接.外连接(左连接.右连接 .全连接).交叉连接,今天统一整合一下,看看他们的区别. 首先建表填充值. 学生表:student(id,姓名,年龄,性别 ) 成绩表 ...
- 我对GIT的理解
git是一个版本或项目代码管理工具.能够方便的管理多个开发人员共同协助开发的代码.在git的管理下,每个开发人员都能同时对项目进行开发,开发人员被划分成不同的分支,每个开发人员都能拥有自己的一个或者多 ...
