我的handler

本文介绍了一个简单的Android应用示例,该应用通过使用Handler和Runnable实现了基本的定时任务功能。当用户勾选CheckBox时,应用将显示一条提示信息,并在三秒后再次更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import android.app.Activity;  
import android.os.Bundle;  
import android.os.Handler;  
import android.os.SystemClock;
import android.widget.Button;  
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;  
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
 
public class TestTimer extends Activity {  
    private Button btnStart;  
    private Button btnStop;  
    private Button btnReset;  
    private TextView tvCounter; 
   
    private CheckBox cb ;
   
    private long count = 0;  
    private boolean run = false;  
 
    private Handler handler = new Handler();  
 
    private Runnable task = new Runnable() {  
 
        public void run() {  
            // TODO Auto-generated method stub  
           
            SystemClock.sleep(3000);
            Toast.makeText(TestTimer.this, "关闭打钩", Toast.LENGTH_SHORT).show();
//            handler.post(task);
        }  
    };  
 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
 
        btnStart = (Button) findViewById(R.id.Button01);  
        btnStop = (Button) findViewById(R.id.Button02);  
        btnReset = (Button) findViewById(R.id.Button03);  
        tvCounter = (TextView) findViewById(R.id.counter);  
        cb = (CheckBox)findViewById(R.id.cb);
       
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
   
   @Override
   public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
    // TODO Auto-generated method stub
    if(arg1){
     Toast.makeText(TestTimer.this, "开启打钩", Toast.LENGTH_SHORT).show();
     
    }else{
     cb.setChecked(false);
     handler.post(task);
     
    }
   }
  });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值