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)的更多相关文章

  1. 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 ...

  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. libevent简介 构成

    libevent简介 libevent是一个事件驱动的网络库,支持跨平台,如Linux, *BSD, MacOS X, Solaris, Windows.支持I/O多路复用,epoll.poll./d ...

  2. Android Studio SDK 更新方法

    通常情况下,下载Android SDK需要连接谷歌的服务器进行下载,由于国内水深火热的网络,速度基本为0.好在国内也有一个更新的镜像地址.本文章介绍如何在不FQ的情况下,使用国内镜像地址,更新andr ...

  3. Zybo智能小车识别图像中的文字

    智能小车识别图像中的文字 [TOC] 运行平台 这次的内容是基于Xilinx公司的Zybo开发板以及其配套的Zrobot套件开发 Zybo上面的sd卡搭载了Ubuntu12.04LTS的linux版本 ...

  4. 学习jax-ws(一)

    1.生成文件时提示class not find ,需要加个cp .,这样就行了 E:\mylearn\learn_webservice\learnJax-ws\bin>wsgen -cp . w ...

  5. Unity3d之Mecanim(新版动画系统)

    1,动画系统配置,2,代码控制动画 原文地址:http://blog.csdn.net/dingkun520wy/article/details/51247491 1,动画系统配置 创建Animato ...

  6. “我爱淘”冲刺阶段Scrum站立会议7

    完成任务: 大事不好,今天的任务还没有完成,没有通过xml文件通过服务器显示到软件中. 计划任务: 实现通过服务器将xml文件中的数据显示到软件中. 遇到问题: 服务器已经配好,并且解析xml文件的代 ...

  7. “我爱淘”冲刺阶段Scrum站立会议4

    完成任务: 完成了搜索界面的Activity的编写. 计划任务: 实现数据库的链接,用户可以查到自己需要的书籍的信息. 遇到问题: 数据库的操作,实现查询功能:

  8. PyDev for Eclipse 简介

    PyDev 安装和配置 安装 PyDev 在安装 PyDev 之前,要保证您已经安装了 Java 1.4 或更高版本.Eclipse 以及 Python.接下来,开始安装 PyDev 插件. 启动 E ...

  9. 转载—“Cache-control”常见的取值有private、no-cache、max-age、must-revalidate等

    转载自http://www.cnblogs.com/igin/archive/2008/05/04/1181056.html 网页的缓存是由HTTP消息头中的“Cache-control”来控制的,常 ...

  10. LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面

    // test20.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> #include< ...