栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android实现倒计时30分钟功能

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android实现倒计时30分钟功能

以30分钟为例写的一个倒计时:
直接上代码

public class MainActivity extends AppCompatActivity {

  private int minute = 30;//这是分钟
  private int second = 0;//这是分钟后面的秒数。这里是以30分钟为例的,所以,minute是30,second是0
  private TextView timeView;
  private Timer timer;
  private TimerTask timerTask;
  //这是接收回来处理的消息
  private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
      if (minute == 0) {
 if (second == 0) {
   timeView.setText("Time out !");
   if (timer != null) {
     timer.cancel();
     timer = null;
   }
   if (timerTask != null) {
     timerTask = null;
   }
 } else {
   second--;
   if (second >= 10) {
     timeView.setText("0" + minute + ":" + second);
   } else {
     timeView.setText("0" + minute + ":0" + second);
   }
 }
      } else {
 if (second == 0) {
   second = 59;
   minute--;
   if (minute >= 10) {
     timeView.setText(minute + ":" + second);
   } else {
     timeView.setText("0" + minute + ":" + second);
   }
 } else {
   second--;
   if (second >= 10) {
     if (minute >= 10) {
timeView.setText(minute + ":" + second);
     } else {
timeView.setText("0" + minute + ":" + second);
     }
   } else {
     if (minute >= 10) {
timeView.setText(minute + ":0" + second);
     } else {
timeView.setText("0" + minute + ":0" + second);
     }
   }
 }
      }
    }

  };


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timeView = (TextView) findViewById(R.id.tv);

    timeView.setText(minute + ":" + second);

    timerTask = new TimerTask() {

      @Override
      public void run() {
 Message msg = new Message();
 msg.what = 0;
 handler.sendMessage(msg);
      }
    };

    timer = new Timer();
    timer.schedule(timerTask, 0, 1000);

  }

  @Override
  protected void onDestroy() {
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
    if (timerTask != null) {
      timerTask = null;
    }
    minute = -1;
    second = -1;
    super.onDestroy();
  }

  @Override
  protected void onStart() {
    super.onStart();
  }

  @Override
  protected void onStop() {
    super.onStop();
  }

  @Override
  protected void onResume() {
    super.onResume();
  }

  @Override
  protected void onRestart() {
    super.onRestart();
  }

  @Override
  protected void onPause() {
    super.onPause();
  }
}

ok,这就完成了。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/158704.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号