by design it’s impossible to update user interface elements from outsidethe main UI thread.

if you’re sharing state between two or more threadsyou always need to synchronize thisshared data using synchronization primitives such as Java’s synchronize and volatilekeywords, or a Lock object.

we highly recommend Java Concurrency in Practice by Brian Goetz.

we’re not allowed toupdate the user interface from a worker thread directly, so there’s no way we canupdate progress that way. Clearly, we need a way to communicate with the UI threadfrom another thread, so that we can send our update messages and have it react tothem.


You could store progress information in a shared variable and access it from boththreads: the worker thread writes to it, and the UI thread periodically reads from it.
But this would require us to synchronize access to it,

Itturns out that there’s an easier way to do these things on Android—Android’s messagepassingfacilities. This approach uses message queues to allow interthread communicationin a controlled, thread-safe manner. Progress information can therefore bepassed from a worker to the UI thread by posting update messages to the UI thread’smessage queue using Android’s Handler and Message classes.

A handler is an object that can be bound to an arbitrary thread (the handler thread).The handler can then be used by other threads to send messages to or even execute
code on the handler thread. Binding is implicit: a handler is always bound to thethread in which it’s being instantiated. If, for instance, a handler is bound to the UIthread, it’ll start monitoring that thread’s message queue. A second thread (theworker) can then use the handler object to send messages to the UI thread by callingits sendMessage(Message) method, or even ask it to execute a method on the UIthread by calling the post(Runnable) method. No additional synchronization is
needed—it just works!

the main UI thread maintains a message loop from which messagescan be routed to a Handler.

The receiving thread reacts by implementing the handleMessage(Message) methoddefined by the Handler.Callback interface. A common approach is to let an activity
implement Handler.Callback and configure the handler object as the object responsiblefor processing a message.

1 Create a Handler object and bind it to the UI thread.
2 Implement the Handler.Callback interface, for example on the Activity.
3 From the download thread, use the handler object to send a message containingthe new status text to the UI thread.
4 In the callback method, read the status text form the message object andupdate the text view.

Message passing can be used to communicate state between threads


//Implement callback interfacepublic class ImageDownloadWithMessagePassing extends Activity implements Handler.Callback{private Handler handler=new Handler(this);//Create/bind handlerprivate Runnable imageDownloader=new Runnable(){//Helper to send status messageprivate void sendMessage(String what){Bundle bundle=new Bundle();bundle.putString("status", what);Message message=new Message();message.setData(bundle);handler.sendMessage(message);}@Overridepublic void run() {// TODO Auto-generated method stub//Call helpersendMessage("Download started");try{URL imageUrl=new URL("http://www.android.com/images/froyo.png");Bitmap image=BitmapFactory.decodeStream(imageUrl.openStream());            if (image != null) {               sendMessage("Successfully retrieved file!");            } else {               sendMessage("Failed decoding file from stream");            }}catch(Exception e){                sendMessage("Failed downloading file!");                e.printStackTrace();}}};   public void startDownload(View source) {      new Thread(imageDownloader, "Download thread").start();   }   @Override   public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.main);   }   @Overridepublic boolean handleMessage(Message msg) {// TODO Auto-generated method stubString text=msg.getData().getString("status");TextView statusText=(TextView)findViewById(R.id.status);statusText.setText(text);return true;}}

Both the handler creation and the callback methodwill be executed on the UI thread. In our download job, we then create a helpermethod D that prepares the message using a Bundle that holds the status text, andthen dispatches the message via the handler object. (Think of a Bundle as being analogousto Java’s Map, but able to pass key-value-pairs even across thread or processboundaries.) We then use this helper in the run method to send our status updates E.These steps are executed on the download thread.

Because the callback is executed on the UI thread, and a Bitmap is parcelable (itimplements the Parcelable interface), we could stick the bitmap into the bundle andpass it over to the callback, too! That way we could immediately update an ImageViewusing the downloaded image.Recall that message passing doesn’t mean we invoke the callback directly. Instead, we post the message to a message queue, which means that queue must be polled periodically by the receiving thread to check for new messages. It turns out that Android handles this for us by automatically creating a message loop for the application’s UI thread. If we were to pass messages between two custom threads instead, then we’d have to handle this ourselves.

clicking on the button will alwaysstart a new download thread, without us having any control over how many threadsrun at once. threads are expensive to create and handle. It would be nice to gain morecontrol over how threads are managed.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. 为什么我喜欢android
  2. Android报表解决方案 使用开源组件iChart
  3. 让洪水猛兽变成温顺小羊——浅谈Android
  4. 把android 主板打造成ip摄像头
  5. Android(安卓)WebView 远程网页 加载本地
  6. 《Android4游戏编程入门经典》读后感
  7. Android开发教程02:Android四大组件简介
  8. 30个高质量并且免费的Android图标【Andro
  9. Android(安卓)获取手机存储信息详解(内存,
  10. Android普及入门