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

时间: 2024-10-27 15:24:56

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 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 refreshe

Android UI编程(4)——Thread、Message、Handler

当应用程序启动时,会开启一个主线程(也就是UI线程),由它来管理UI,监听用户点击,来响应用户并分发事件等.所有一般在主线程中不要执行比较耗时的操作,如延时.下载网络数据.死循环,否则出现ANR错误.所以就将这些操作放在子线程中,但是由于Android UI线程是不安全的,所有只能在主线程中更新UI.使用Thread来创建子线程.使用Message来存储数据.使用Handler来处理消息数据. 总结: 1.子线程与UI主线程之间通过Message来传递数据,需要创建一个新类(MyHandler)

Android子线程更新UI主线程方法之Handler

背景: 我们开发应用程序的时候,处于线程安全的原因子线程通常是不能直接更新主线程(UI线程)中的UI元素的,那么在Android开发中有几种方法解决这个问题,其中方法之一就是利用Handler处理的. 下面说下有关Handler相关的知识. 多线程一些基础知识回顾:在介绍Handler类相关知识之前,我们先看看在Java中是如何创建多线程的方法有两种:通过继承Thread类,重写Run方法来实现通过继承接口Runnable实现多线程 具体两者的区别与实现,看看这篇文章中的介绍:http://de

Android关于线程更新UI的方法

Android关于线程更新UI的方法 在一个Android 程序开始运行的时候,会单独启动一个Process.默认的情况下,所有这个程序中的Activity或者Service(Service和 Activity只是Android提供的Components中的两种,除此之外还有Content Provider和Broadcast Receiver)都会跑在这个Process.   一个Android 程序默认情况下也只有一个Process,但一个Process下却可以有许多个Thread.   在

Android中子线程和UI线程之间通信的方式

Android中子线程和UI线程之间通信的详细解释 1.在多线程编程这块,我们经常要使用Handler,Thread和Runnable这三个类,那么他们之间的关系你是否弄清楚了呢?下面详解一下. 2.首先在开发Android应用时必须遵守单线程模型的原则: Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行. 3.Handler: (1).概念: Handler是沟通Activity 与Thread/runnable的桥梁.而Handler是运行在主UI线程中的,它与子线程

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

50个Android开发人员必备UI效果源码[转载] http://blog.csdn.net/qq1059458376/article/details/8145497 Android 仿微信之主页面实现篇Android 仿微信之界面导航篇Android 高仿QQ 好友分组列表Android 高仿QQ 界面滑动效果Android 高仿QQ 登陆界面Android 对Path的旋转效果的拓展Android高仿360安全卫士布局源码Android SlidingDrawer 滑动抽屉效果Androi

Android基础知识(1)——UI编程

我学习android一段时间了,看着大牛们的各种神博客,心里也痒痒的,希望有一天也能成为他们一样. 我知道,这些都是一滴一滴的积累,所有我也需要找到我的学习方法,打好基础,做出属于我自己的成果. 当然,作为一名菜鸟程序员,更加要懂得把知识整理归类,方便记忆. ----------------------------------------------------------- 在学校里听老师讲课,总会让学生误会程序员的主要工作不是界面美化,那都是美工做得事情.但随着移动开发的不断发展,在软件开发

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

转:http://www.cnblogs.com/setoutsoft/p/4996870.html 前言 在Windows平台上开发客户端产品是一个非常痛苦的过程,特别是还要用C++的时候.尽管很多语言很多方法都可以开发Windows桌面程序,目前国内流行的客户端产品都是C++开发的,比如QQ,YY语音,迅雷等.快速,稳定是我认为的应用软件开发框架最基本的要求,对于UI还有两个要求就是界面美观,配置灵活.C++语言满足了快速的要求,传统的客户端软件开发框架如MFC,WTL等满足了稳定的要求.然

学习IOS开发UI篇--UI知识点总结(四) UITabelView/UITableViewCell

UITabelView:常用属性 @property (nonatomic)          CGFloat    rowHeight;             // will return the default value if unset @property (nonatomic)          CGFloat     sectionHeaderHeight;   // will return the default value if unset @property (nonatom