本文通过“使用新线程计算质数”这样一个demo,简单讲解如何在Android中使用Handler进行多线程开发。
为了更好地理解Handler的工作原理,先介绍一下Handler一起工作的几个组件。
- Message:Handler接收和处理的消息对象
- Looper:每个线程只能拥有一个Looper。它的loop方法负责读取MessageQueue中的消息,读到消息之后就把消息交给发送该消息的Handler进行处理。
- MessageQueue:消息队列。程序创建Looper对象时,会在它的构造器中创建MessageQueue对象。
在线程中使用Handler的步骤如下:
- 调用Looper的prepare()方法为当前线程创建Looper对象。
- 有了Looper之后,创建Handler子类的实例,重写handleMessage方法。在本实例中该方法用来处理计算质数的逻辑。
- 调用Looper的loop()方法启动Looper。
java代码
public class MainActivity extends Activity {
private EditText editText;
private TextView numText;
private CalThread calThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
calThread = new CalThread();
//启动线程
calThread.start();
}