一、为什么要用Handler
由于android的UI操作不是线程安全的,所以android只允许UI线程(主线程)修改UI组件的状态,但是我们很多时候需要用其他线程来修改UI组件的属性,那就要使用Handler消息了。
二、handler的作用
1、在新启动的线程中发送消息
2、在主线程接收并处理消息
android中的handler是通过回调的方式来实现,开发者只需重写Handler的方法,在新线程中发送消息到MessageQueue,Handler会不断的从MessageQueue中获取消息。
三、Handler、Looper、MessageQueue 解析。
1、每个线程值允许一个Looper,Looper方法负责读取MessageQueue中的消息,并把消息传递给Headler.。启动Looper,只需调用prepare()方法。
2、MesseQueue 消息队列,负责管理Message,每创建Looper的时候就会自动创建MessageQueue对象。
四、使用新线程计算质数:
布局文件:
<span style="font-family:Courier New;font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText_prime"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="提交"
android:onClick="cal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout></span>
</pre><span style="color:#ff0000"><strong>注:Button里面通过标签 绑定了一个监听器cal。</strong></span><p></p><p></p><p>Activity代码:</p><p></p><pre name="code" class="java"><span style="font-family:Courier New;font-size:14px;">package com.example.lenovo.ui_two;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lenovo on 2016/6/4.
*/
public class Prime extends AppCompatActivity {
static final String UPPER_NUM = "upper";
EditText mEditText;
CalThread mCalThread;
//定义一个线程类
class CalThread extends Thread{
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
//定义处理发送消息的方法
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x123) {
int upper = msg.getData().getInt(UPPER_NUM);
List<Integer> list = new ArrayList<Integer>();
outer:
for (int i = 2; i <= upper; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i != 2 && i % j == 0) {
continue outer;
}
}
list.add(i);
}
//使用Toast显示统计出来的所有质数
Toast.makeText(Prime.this, list.toString(), Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prime_layout);
mEditText = (EditText) findViewById(R.id.editText_prime);
mCalThread = new CalThread();
//启动线程
mCalThread.start();
}
//为按钮的点击事件提供事件处理方法
public void cal(View source){
//创建消息
Message mgs = new Message();
mgs.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM,Integer.parseInt(mEditText.getText().toString()));
mgs.setData(bundle);
//向新线程中的handler发送消息
mCalThread.mHandler.sendMessage(mgs);
}
}</span>