每隔1秒刷新一次文本内容显示时间

// 获得文字控件
private TextView tipView = null;

tipView = (TextView) findViewById(R.id.timeText);

Handler handler = new Handler();

//启动runnable任务

handler.postDelayed(runnable,0);

//每隔1秒钟更新界面

private Runnable runnable = new Runnable(){
  @Override
  public void run() {
   this.update();

 //延迟一秒重新运行任务
   handler.postDelayed(runnable, 1000);
  }
 
  private void update(){
   s++;
   System.out.println("------------->s="+s);
   if(s / 3600 >= 1){
    System.out.println("-------------->小时");
    //小时数
    h = h + 1;
    //分钟和秒钟归零
    m = 0;
    s = 0;
   }
  
   if(s / 60 >= 1){
    System.out.println("-------------->分钟");
    m = m + 1;
    s = 0;
   }
   String str = "总共进行时间:" + h + "小时" + m + "分" + s + "秒|每15分钟自动保存";
   tipView.setText(str);
  }
};

方法二:开启新的线程 每隔1秒刷新一次控件

private boolean isRun =false;

//线程循环运行

isRun = true;
new Thread(RecorderActivity.this).start();

@Override
public void run() {
  while (isRun) {
   s++;
   System.out.println("------------->s="+s);
   if(s / 3600 >= 1){
    System.out.println("-------------->小时");
    //小时数
    h = h + 1;
    //减去小时数的秒还剩多少秒
    m = 0;
    s = 0;
   }
  
   if(s / 60 >= 1){
    System.out.println("-------------->分钟");
    m = m + 1;
    s = 0;
   }
   Message message = Message.obtain();
   // 总共进行时间:0小时0分23秒|每15分钟自动保存
   String str = "总共进行时间:" + h + "小时" + m + "分" + s + "秒|每15分钟自动保存";
   message.obj = str;
   handler.sendMessage(message);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
}


//更新UI

private Handler handler = new Handler(){
  @Override
  public void handleMessage(Message msg) {
   super.handleMessage(msg);
   String timeMsg = (String) msg.obj;
   tipView.setText(timeMsg);
  }
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值