Handler
1.为什么要用Handler
android在设计的时候就封装了一套消息创建、传递、处理。如果不遵循就不能更新UI信息,就会报出异常。
2.什么是Handler
handler是Android给我们提供用来更新UI的一套机制,也是一套消息处理机制,我们可以发消息,也可以通过它处理消息。
3.什么是Looper
Looper即:有消息循环的线程。
在Android里线程分为有消息循环的线程和没有消息循环的线程,有消息循环的线程一般都会有一个Looper,这个事android的新概念。主线程(UI线程)就是一个消息循环的线程。针对这种消息循环的机制,引入一个新的机制Handle,有消息循环,就要往消息循环里 面发送相应的消息,自定义消息一般都会有对应的处理,消息的发送和清除,消息的处理,把这些都封装在Handle里面,注意Handle只是针对那些有Looper的线程,不管是UI线程还是子线程,只要有Looper,就可以往消息队列里面添加东西,并做相应的处理。
4.什么是MseeageQueue
MessageQue:就是一个消息队列,可以向其中添加消息并处理消息。
5.Handler怎么用
1、runOnUiThread()方法
2、handler.post()方法
3、handler.sendMessage()方法
4、view.post()方法。
6.案例解析—-倒计时Demo
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.lenovo.myapplication.MainActivity">
<TextView
android:id="@+id/download_tips"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="正在下载"/>
<Button
android:id="@+id/download_btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="开始下载"/>
</LinearLayout>
package com.example.lenovo.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button downloadBtn;
private TextView downloadTips;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindID();
downloadBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
downloadTips.setText("正在下载");
//启动子线程,模拟10秒钟
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(5000);
}catch (InterruptedException e){
e.printStackTrace();
}
downloadTips.setText("下载完成");
}
}).start();
}
});
}
private void bindID() {
downloadBtn=findViewById(R.id.download_btn);
downloadTips=findViewById(R.id.download_tips);
}
}