Android通过Handler传递消息

 Handler类的主要作用有两个:

  • 在新启动的线程中发送消息
  • 在主线程中获取、处理消息

下面通过一个进度条Progress记录Handler类怎么获取处理消息

进度条的进度是不断更新的,调用postDelayed方法每100毫秒更新一次,当进度条达到100时Handler调用sendMessage方法发送一条消息,重写handleMessage方法接收这条消息,在方法中写下一步事件
Thread thread = new Thread(new Runnable() { @Override public void run() { if (value < 100) { value+=5; progressDialog.setProgress(value); handler.postDelayed(thread, 100); }else{ Message msg= Message.obtain(); msg.what = 1; handler.sendMessage(msg);//发送消息 } } });
Handler  handler = new Handler(){
public void handleMessage(Message msg){//重写handleMessage方法,注意方法名必须一致
super.handleMessage(msg);
if(msg.what==1) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}

}
};;

 效果如图:

接收消息前:

接收消息后:

 

原文地址:https://www.cnblogs.com/lyd447113735/p/8027534.html