Android实现简单计时器功能

本文实例为大家分享了Android实现简单计时器的具体代码,供大家参考,具体内容如下

布局

在res/layout 下进行布局





 
 
 

MainActivity

package com.test;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


 private int seconds = 0;
 private boolean running = false; //计时状态
 private boolean wasRunning = false; //保存running的状态

 //app进入后台,暂停计时
 @Override
 protected void onStop() {
 super.onStop();
 wasRunning = running;
 running = false;
 }

 //重新进入app,开始计时
 @Override
 protected void onStart() {
 super.onStart();
 if(wasRunning) running = true;
 }

 //失去焦点(如分屏),暂停计时
 @Override
 protected void onPause() {
 super.onPause();
 wasRunning = running;
 running = false;
 }

 //获得焦点,重新开始计时
 @Override
 protected void onResume() {
 super.onResume();
 if(wasRunning) running = true;
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 //获取保存的状态
 if(savedInstanceState!=null){
  seconds = savedInstanceState.getInt("seconds");
  running = savedInstanceState.getBoolean("running");
  wasRunning = savedInstanceState.getBoolean("wasRunning");
 }
 runTime();
 }

 /**
 *保存状态
 */
 @Override
 public void onSaveInstanceState(Bundle saveInstanceState) {

 super.onSaveInstanceState(saveInstanceState);
 saveInstanceState.putInt("seconds",seconds);
 saveInstanceState.putBoolean("running",running);
 saveInstanceState.putBoolean("wasRunning",wasRunning);
 }
 /**
 * 响应button的onClick事件
 * 方法名和onClick的值一致
 */
 public void onClickStart(View button){
 running = true;
 }
 public void onClickStop(View button){
 running = false;
 }
 public void onClickReset(View button){
 running = false;
 seconds = 0;
 }

 /**
 * 注意 ui线程不能被堵塞,因此不能在ui线程中调用sleep方法
 * 只允许ui线程更新界面,不能在后台线程更新界面
 *
 * ** 使用ui线程的Handler定时更新 **
 * 将任务封装到 Runnable的run方法中 ,通过Handler的
 * post(立即提交任务)或postDelayed(实现定时调度)方法提交到ui线程
 */
 private void runTime(){
 final Handler handler = new Handler();
 handler.post(new Runnable() {
  @Override
  public void run() {
  final TextView textView = findViewById(R.id.timeView);
  int hour = seconds /3600%24;
  int minute = seconds%3600/60;
  String time = String.format("%02d:%02d:%02d",hour,minute,seconds%60);
  textView.setText(time);
  if(running) seconds++;
  handler.postDelayed(this,1000);
  }
  }
 );

 }
}

测试

Android实现简单计时器功能_第1张图片

完成

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Android实现简单计时器功能)