Life is short , play more!
本文来自lihao's Blog,转载请注明。

otto的代码  https://github.com/square/otto

otto的一些介绍 http://corner.squareup.com/2012/07/otto.html

一 为了让android 应用更解耦, 降低代码的耦合度.  为什么不用android自己的一些现成, handler, 或者asynctask呢? 个人觉得otto更方便使用, 封装了更高级灵活的用法.

1. create otto bus (事件总线)

2. ui threads:  register  bus  and  subscribe

3. task threads:  post event to bus

4. ui threads : recieve event from bus, and do something , change ui ,soon.

我们不需要在task threads 里调用任何ui的内容, 只需要发送事件消息即可. 大大解耦了我们的代码模块.

二 关于threads ,  handler, asynctask , 可以看vogella免费的教程, 写的非常专业. 大家可以访问学习.

三  下面是hqt在stack overflow上的关于handler, asyntask 的一些回答.

AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do withHandler or AsyncTask, you can achieve using a Thread too.

What Handler and AsyncTask really help you with?

The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn’t thread-safe (in most of time), in other words, DANGEROUS.

That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.

Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers

I want to emphasize on two points:

1) Easy use of the UI thread (so, use when caller thread is UI Thread).

2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).

There are many things in this post I haven’t said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..

@: when you read Android document, you will see:

Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue

They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)


电子邮件地址不会被公开。 必填项已用*标注