Handler类简介
1.Handler 类的两个主要作用
>1.在新启动的线程中发送消息
>2.在主线程中获取、处理消息
Handler类包含如下方法用于发送、处理消息
void handlerMessage(Message msg):处理消息的方法,通常重写该方法
final boolean hasMessages(int what):检查消息队列中是否包含what属性为指定值的消息
final boolean hasMessages(int what,Object object):检查消息队列中是否包含what属性为指定值且object属性为指定对象的消息
sendEmptyMessage(int what):发送空消息
final boolean sendEmptyMessageDelayed(int what,long delayMilis):指定多少毫秒之后发送空消息
final boolean sendMessage():立即发送消息
final boolean sendMessageDelayed(Message mag,long delayMilis)指定多少毫秒之后发送消息
实例:自动播放动画
package com.yunzhu.handlerdemo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
//定义周期性显示图片的ID
int[] imageIds=new int[]{
R.drawable.h1, R.drawable.h2, R.drawable.h3, R.drawable.h4, R.drawable.h5
};
int currentImageId=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView show = (ImageView) findViewById(R.id.imageView);
final Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
show.setImageResource(imageIds[currentImageId++%imageIds.length]);
}
}
};
//定义一个计时器,让该计时器周期性的执行指定任务
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myHandler.sendEmptyMessage(0x123);
}
},0,1200);
}
}
Handler、Loop、messageQueue的工作原理
常与Handler一起工作的几个组件
Message:Handle接收和处理的消息对象
Looper:每个线程只能拥有一个Looper,他的loop方法负责读取MessageQueue中的消息,读到消息之后就把消息发送给该消息的Handler进行处理。
MessageQueue:消息队列,他采用先进先出的方式管理Meaasge.程序创建Looper对象时会在他的构造器中创建Looper对象,
在线程中使用Handler的步骤:
1.调用Looper的prepare()方法为当前线程创建Looper对象,创建Looper对象时他的构造器会创建与之配套的MessageQueue.
2.创建Handler子类的实例,重写handlerMeaage()方法
3.调用Looper的loop()方法启动Looper.
实例:计算质数
package com.yunzhu.handlerdemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yu on 2015/8/15.
*/
public class Calprime extends ActionBarActivity{
static final String UPPER_NUM="upper";
EditText etNum;
CalThread calThread;
//定义一个线程类
class CalThread extends Thread{
public Handler mHandler;
@Override
public void run() {
Looper.prepare();//为当前线程创建Looper对象,创建Looper对象时,他的构造器会创建与之配套的MessageQueue
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
int upper=msg.getData().getInt(UPPER_NUM);
List<Integer> mums=new ArrayList<Integer>();
outer:
//计算从2开始到upper的所有质数
for(int i=2;i<=upper;i++){
//用i除以从2开始到i的平方根的所有数
for(int j=2;j<=Math.sqrt(i);j++){
//如果可以整除,则表明这个数不是质数
if(i!=2&&i%j==0){
continue outer;
}
}
mums.add(i);
}
Toast.makeText(Calprime.this,mums.toString(),Toast.LENGTH_SHORT).show();
}
}
};
Looper.loop();
super.run();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
etNum=(EditText)this.findViewById(R.id.editText);
calThread=new CalThread();
calThread.start();
}
public void cal(View view){
//创建消息
Message msg=new Message();
msg.what=0x123;
Bundle bundle=new Bundle();
bundle.putInt(UPPER_NUM,Integer.parseInt(etNum.getText().toString()));
msg.setData(bundle);
//向新线程中的Handler发送消息
calThread.mHandler.sendMessage(msg);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_weight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="计算"
android:onClick="cal"
/>
</LinearLayout>