android 学习记录—————Handler的使用

本文介绍了Android中如何通过Handler类安全地更新UI线程。主要内容包括:如何实现Handler.Callback接口或Handler内部类,以及如何使用sendMessage方法发送Message对象来更新UI。

为了保证线程安全,android使用handler类来实现其他线程对于UI线程的更新。

 

handler的使用过程为:

 

为了更新UI线程里面的数据,所在Activity必须实现 android.os.Handler.Callback 接口,或者实现Handler的内部类。

 

不管是实现handler内部类还是继承Callback接口,需要重写的方法为handleMessage

 

   @Override
    public boolean handleMessage(Message msg) {
   
       
switch(msg.what)
        {
       
case 0:
            Bundle date
=msg.getData();
            txt.setText(String.valueOf(date.getInt(
"time")));
            break;

        }
       
return false;
    }

 

当其中一个子线程需要操纵UI线程时,调用Handler对象里sendMessage方法发送一个Message对象即可:

       

        

        Message msg=new Message();
        Bundle date
= new Bundle();// 存放数据
        date.putInt("time", total);
        msg.setData(date);
        msg.what
=0;
        myHandler.sendMessage(msg);
另一种方法也可以实现这个功能:
        Message msg=myHandler.obtainMessage();
        Bundle date = new Bundle();// 存放数据
       date.putInt("time", total);
       msg.setData(date);
       msg.what=0;
       msg.sendToTarget();

msg.what来区分对UI的修改来自哪个不同的线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值