主要用途:
- to schedule messages and runnables to be excuted as some point in the future(未来某事做某事)
- to enqueue an action to be performed on a different thread than you own(线程间通信)
下面通过代码演示学习:
我们在这里想要实现:点击按钮,进入HandlerActivity,里面来通过handler执行一个 postDelayed
的方法,通过这个方法,延时三秒钟处理一个事情————跳转到另一个activity,
HandlerActivity中的代码如下:
public class HandlerActivity extends AppCompatActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
mHandler=new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent=new Intent(HandlerActivity.this, ButtonActivity.class);
startActivity(intent);
}
}, 3000);
}
}
再来一个很直观的线程的通信,在新的线程中发送消息,在主线程中处理,成功会弹出一个Toast
public class HandlerActivity extends AppCompatActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
ToastUtil.showMsg(HandlerActivity.this,"线程通信成功");
break;
}
}
};
new Thread(){
@Override
public void run() {
super.run();
Message message = new Message();
message.what=1;
mHandler.sendMessage(message);
}
}.start();
}
}
可以实现点按钮进入HandlerActivity,线程Thread()发出一个消息,这个消息在主线程中通过handleMessage进行处理,通过message的参数不同进行相应的处理。