为什么要用Handler?
子线程一般是用来进行耗时计算的,由于子线程不能更改UI,当子线程完成了耗时计算需要更新UI的时候怎么办呢,我们就需要传递一个消息给主线程,告知该进行什么操作,这就需要用到Handler
什么是Handler?
Handler主要用于异步消息的处理:当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分在消息队列中逐一将消息取出,然后对消息进行处理,也就是发送消息和接收消息不是同步的处理。 这种机制通常用来处理相对耗时比较长的操作。
什么是Looper?
Looper是专门来处理消息的,Looper会无限循环检查消息队列里是否有新的消息,如果有就进行处理,如果没有则等待,Handler创建的时候会采用当前线程的Looper来构造消息循环系统。
什么是MessageQueue?
MessageQueue意思是消息队列,用来储存线程发出的消息。子线程发出消息后会先进入MessageQueue,然后由Looper处理,Looper处理消息的时候是一条一条进行处理的,所以消息的处理是阻塞形式的,处理完这条消息才会抽出下一条消息进行处理
倒计时Demo
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置时间" />
<EditText
android:id="@+id/download_et"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:numeric="integer" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="秒" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/download_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="倒计时结束"
android:textSize="30dp" />
<Button
android:id="@+id/download_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始下载" />
</LinearLayout>
</LinearLayout>